package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.config.*;
import com.qingcloud.adminbackend.entity.domain.SysDomain;
import com.qingcloud.adminbackend.entity.equipment.*;
import com.qingcloud.adminbackend.entity.factor.SysSensorFactor;
import com.qingcloud.adminbackend.entity.product.SysProductType;
import com.qingcloud.adminbackend.entity.robot.RobotDto;
import com.qingcloud.adminbackend.entity.robot.RobotInfo;
import com.qingcloud.adminbackend.entity.sensor.SensorParam;
import com.qingcloud.adminbackend.entity.sensor.SensorParamDTO;
import com.qingcloud.adminbackend.entity.sensor.SysSensor;
import com.qingcloud.adminbackend.entity.sensor.SysSensorFactorConfigDTO;
import com.qingcloud.adminbackend.entity.stationequipment.OptStationEquipment;
import com.qingcloud.adminbackend.entity.stationgroup.SysStationGroupEquipment;
import com.qingcloud.adminbackend.entity.sysorder.SysOrder;
import com.qingcloud.adminbackend.entity.sysorder.SysOrderEquipment;
import com.qingcloud.adminbackend.entity.sysorg.SysUserOrgMgr;
import com.qingcloud.adminbackend.entity.sysstation.*;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.entity.userrole.UserRoleVO;
import com.qingcloud.adminbackend.enums.ProductTypeEnum;
import com.qingcloud.adminbackend.exception.WmCommonException;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.pojo.equipment.EquipmentDecodeMessage;
import com.qingcloud.adminbackend.pojo.equipment.EquipmentDecoder;
import com.qingcloud.adminbackend.pojo.equipment.GatewayInfo;
import com.qingcloud.adminbackend.pojo.product.ProductParseData;
import com.qingcloud.adminbackend.provider.fusion.DataFusionApiHelper;
import com.qingcloud.adminbackend.service.IRobotService;
import com.qingcloud.adminbackend.service.ISysEquipmentService;
import com.qingcloud.adminbackend.utils.AesUtil;
import com.qingcloud.adminbackend.utils.CommonUtil;
import com.qingcloud.adminbackend.utils.DateUtil;
import com.qingcloud.adminbackend.utils.ExcelUtil;
import com.qingcloud.adminbackend.utils.StringUtil;
import com.qingcloud.adminbackend.entity.config.*;
import com.qingcloud.adminbackend.entity.equipment.*;
import com.qingcloud.adminbackend.entity.sysstation.*;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.utils.*;
import com.qingcloud.base.api.remote.eqcenter.EqcenterApi;
import com.qingcloud.base.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备表基本信息表 服务实现类
 * </p>
 *
 * @author luozehua
 * @since 2018-11-19
 */
@Service
@Slf4j
public class SysEquipmentServiceImpl extends ServiceImpl<SysEquipmentMapper, SysEquipment> implements ISysEquipmentService {

    @Resource
    private SysEquipmentMapper sysEquipmentMapper;
    @Resource
    private SysDomainMapper sysDomainMapper;
    @Resource
    private SysStationMapper sysStationMapper;
    @Resource
    private SysStationEquipmentMapper sysStationEquipmentMapper;
    @Resource
    private SysOrderEquipmentMapper sysOrderEquipmentMapper;
    @Resource
    private SysStationGroupEquipmentMapper sysStationGroupEquipmentMapper;
    @Resource
    private SysStationGroupMapper sysStationGroupMapper;
    @Resource
    private SysSensorFactorConfigMapper sysSensorFactorConfigMapper;
    @Resource
    private SysDictionaryConfigMapper sysDictionaryConfigMapper;
    @Resource
    private BaseServiceImpl baseService;

    @Resource
    private SysSensorMapper sysSensorMapper;
    @Resource
    private SysSensorFactorMapper sysSensorFactorMapper;

    @Resource
    private SysCommonConfigMapper sysCommonConfigMapper;
    @Resource
    private SysProductTypeMapper sysProductTypeMapper;

    @Resource
    private SysOrderMapper sysOrderMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserOrgMgrMapper sysUserOrgMgrMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserOrderStationmgrMapper sysUserOrderStationmgrMapper;
    @Resource
    private IRobotService robotService;

    @Resource
    private SysEquipmentBackupMapper sysEquipmentBackupMapper;

    @Resource
    private DataFusionApiHelper dataFusionApiHelper;

    @Resource
    private EquipmentDecodeRecordMapper decodeRecordMapper;

    @Resource
    private EqcenterApi eqcenterApi;

    private static final Integer PROID = 1;

    private static final Integer CITYID = 2;
    private static final Integer DISTID = 3;

    /**
     * 设备池的设备
     *
     * @param equipmentListBO
     * @return
     */
    @Override
    public List<EquipmentListDTO> equipmentPool(EquipmentListBO equipmentListBO) {
        return baseMapper.equipmentPool(equipmentListBO);
    }

    /**
     * 订单内设备
     *
     * @param equipmentListBO
     * @return
     */
    @Override
    public List<EquipmentListDTO> orderEquipment(EquipmentListBO equipmentListBO) {
        return baseMapper.orderEquipment(equipmentListBO);
    }

    @Override
    public AjaxResult orderEquipmentMoveToYichu(EquipmentDTO equipmentDTO, String userId) {
        //查询订单下的设备
        List<SysStationEquipment> equipments = sysOrderEquipmentMapper.findEquipmentsByOrderId(equipmentDTO.getOrderId(), null);
        //记录要解绑的设备
        List<String> deleteList = new ArrayList<>();
        equipments.forEach(it -> {
            if (!equipmentDTO.getEquipmentIds().contains(it.getEquipmentId())) {
                deleteList.add(it.getEquipmentId());
            }
        });
        //添加新的订单关联
        if (equipmentDTO.getEquipmentIds().size() > 0) {
            AjaxResult ajaxResult = orderToEquipment(equipmentDTO, userId);
            if (ajaxResult.getErroCode() == WamingConstant.FAILURE) {
                return ajaxResult;
            }
        }
        //解除订单和设备的关系
        if (deleteList.size() > 0) {
            equipmentDTO.setEquipmentIds(deleteList);
            return deleteEquipmentsByIds(equipmentDTO);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "关联成功");
    }

    /**
     * 产品系列
     *
     * @param productSeries
     * @return
     */
    public String productSeries(String productSeries) {
        if ("0".equals(productSeries)) {
            return "室内";
        }
        if ("1".equals(productSeries)) {
            return "微站";
        }
        if ("2".equals(productSeries)) {
            return "便携式";
        }
        if ("3".equals(productSeries)) {
            return "无人机";
        }
        return null;
    }

    /**
     * 删除订单关联的设备
     *
     * @param equipmentDTO
     * @return
     */
    @Override
    public AjaxResult deleteEquipmentsByIds(EquipmentDTO equipmentDTO) {
        //订单下的设备
        List<SysStationEquipment> equipmentBOs = sysOrderEquipmentMapper.findEquipmentsByOrderId(equipmentDTO.getOrderId(), equipmentDTO.getEquipmentIds());
        List<String> equipmentIds = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        List<String> stationIds = new ArrayList<>();
        equipmentBOs.stream().forEach(it -> {
            if (StringUtils.isEmpty(it.getStationId())) {
                equipmentIds.add(it.getEquipmentId());
            } else {
                stationIds.add(it.getStationId());
            }
            ids.add(it.getEquipmentId());
        });
        if (equipmentIds.size() > 0) {
            //删除订单关联的设备
            sysOrderEquipmentMapper.deleteEquipmentsByIds(equipmentDTO.getOrderId(), equipmentIds);
            //删除只有设备的数据
            sysOrderEquipmentMapper.deleteStationgroupEquipmentsByIds(equipmentIds);
        }
        if (stationIds.size() > 0) {
            for (String stationId : stationIds) {
                //修改订单下的设备关系表
                sysOrderEquipmentMapper.updateEquipmentsByIds(equipmentDTO.getOrderId(), stationId);
                //清空设备组下设备绑定关系
                sysOrderEquipmentMapper.updateStationgroupEquipmentsByIds(stationId);
            }
            //批量解除设备与检测的绑定关系
            sysStationEquipmentMapper.updateStationEquipments(equipmentBOs);
        }
        if (ids.size() > 0) {
            //修改订单状态
            sysEquipmentMapper.updateEquipmentCatagory(2, ids);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "操作成功");
    }

    /**
     * 订单关联设备Api(从设备池移入)
     *
     * @param equipmentDTO
     * @param userId
     * @return
     */
    @Override
    public AjaxResult orderToEquipment(EquipmentDTO equipmentDTO, String userId) {
        List<EquipmentBO> list = baseMapper.findStationEquipment(equipmentDTO);
        List<String> ids = new ArrayList<>();
        for (EquipmentBO equipmentBO : list) {
            equipmentBO.setCreateBy(userId);
            equipmentBO.setCreateDt(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
            ids.add(equipmentBO.getEquipmentId());
        }
        //验证设备是否绑定别的订单
        List<String> list1 = sysOrderEquipmentMapper.findEquipmentsByNotOrderId(equipmentDTO.getOrderId(), equipmentDTO.getEquipmentIds());
        if (list1.size() > 0) {
            String equipmentIds = StringUtil.listToString(list1);
            return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmentIds + "已经绑定别的订单！", null);
        }
        if (list.size() > 0) {
            //删除设备，避免重复
            sysOrderEquipmentMapper.deleteEquipmentsByStationIds(equipmentDTO.getOrderId(), list);
            //订单绑定设备
            sysOrderEquipmentMapper.orderToEquipment(list);
        }
        if (ids.size() > 0) {
            //修改订单状态
            sysEquipmentMapper.updateEquipmentCatagory(2, ids);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "关联成功");
    }

//    /**
//     * 网格化设备、监测点导入
//     *
//     * @param file
//     * @param orderId
//     * @param userId
//     * @return
//     * @throws IOException
//     * @throws InvalidFormatException
//     */
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public AjaxResult equipmentStationExcelWGH(MultipartFile file, String orderId, String userId) throws IOException, InvalidFormatException {
//        List<SysDomain> proList = sysDomainMapper.getAllDomainDTOById(PROID);
//        List<SysDomain> cityList = sysDomainMapper.getAllDomainDTOById(CITYID);
//        List<SysDomain> distList = sysDomainMapper.getAllDomainDTOById(DISTID);
//        TypeConfigDTO typeConfigDTO = setTypeConfig();
//        InputStream in = file.getInputStream();
//        Workbook workbook = WorkbookFactory.create(in);
//        if (in != null) {
//            in.close();
//        }
//        if (workbook != null) {
//            // 遍历每个Sheet
//            Sheet sheet = workbook.getSheetAt(0);
//            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
//            // 遍历每一行
//            List<SysEquipment> sysEquipments = new ArrayList<>();
//            List<String> equipmentIds = new ArrayList<>();
//            List<SysStation> stations = new ArrayList<>();
//            List<String> stationIds = new ArrayList<>();
//            List<SysStationEquipment> sysStationEquipments = new ArrayList<>();
//            List<EquipmentBO> sysOrderEquipments = new ArrayList<>();
//            for (int r = 1; r < rowCount; r++) {
//                Row row = sheet.getRow(r);
//                /*设备数据*/
//                AjaxResult ajaxResult = setSysEquipment(row, r, userId);
//                if (ajaxResult.getErroCode() != WamingConstant.SUCCESS) {
//                    return ajaxResult;
//                }
//                SysEquipment sysEquipment = (SysEquipment) ajaxResult.getResult();
//                if (equipmentIds.contains(sysEquipment.getEquipmentId())) {
//                    return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + sysEquipment.getEquipmentId() + "重复");
//                }
//                equipmentIds.add(sysEquipment.getEquipmentId());
//                sysEquipments.add(sysEquipment);
//                /*监测点数据*/
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(14)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第15列监测点编号不能为空！", null);
//                }
//                SysStation sysStation = new SysStation();
//                sysStation.setEquipmentId(sysEquipment.getEquipmentId());
//                //监测点编号
//                sysStation.setStationId(ExcelUtil.getCellStringValue(row.getCell(14)));
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(15)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第16列监测点名称不能为空！", null);
//                }
//                //监测点名称
//                sysStation.setStationName(ExcelUtil.getCellStringValue(row.getCell(15)));
//                //监测点种类
//                String equipmentType = ExcelUtil.getCellStringValue(row.getCell(16));
//                if (StringUtils.isEmpty(equipmentType)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第17列监测点种类不能为空！", null);
//                }
//                //监测点类型及种类处理
//                String stType = ExcelUtil.getCellStringValue(row.getCell(17));
//                if (StringUtils.isEmpty(stType)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第19列监测点类型不能为空！", null);
//                }
//                //监测点类型及种类处理
//                matchingType(equipmentType, stType, sysStation, typeConfigDTO);
//                String value = ExcelUtil.getCellStringValue(row.getCell(18));
//                if (StringUtils.isEmpty(value)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第19列监测点状态不能为空！", null);
//                }
//                //监测点状态
//                int sattusValue = stationStatus(value);
//                if (sattusValue == -1) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第19列监测点状态错误！", null);
//                }
//                sysStation.setStatus(sattusValue);
//                //监测点类型
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(19)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第20列省份不能为空！", null);
//                }
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(20)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第21列城市不能为空！", null);
//                }
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(21)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第22列区县不能为空！", null);
//                }
//                //省市区
//                fillData(row.getCell(19), row.getCell(20), row.getCell(21), sysStation, proList, cityList, distList);
//                //地址
//                sysStation.setAddr(ExcelUtil.getCellStringValue(row.getCell(22)));
//                //gps纬度
//                sysStation.setLatReal(new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(23))));
//                //gps经度
//                sysStation.setLngReal(new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(24))));
//                //杆号
//                sysStation.setPoleId(ExcelUtil.getCellStringValue(row.getCell(25)));
//                //电表号
//                sysStation.setAmmeterNo(ExcelUtil.getCellStringValue(row.getCell(26)));
//                sysStation.setCreateBy(userId);
//                sysStation.setCreateDt(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
//                if (stationIds.contains(sysStation.getStationId())) {
//                    return new AjaxResult(WamingConstant.FAILURE, "导入的监测点编号" + sysStation.getStationId() + "重复");
//                }
//                stationIds.add(sysStation.getStationId());
//                stations.add(sysStation);
//                //监测点绑定设备
//                SysStationEquipment sysStationEquipment = new SysStationEquipment();
//                sysStationEquipment.setStationId(sysStation.getStationId());
//                sysStationEquipment.setEquipmentId(sysEquipment.getEquipmentId());
//                sysStationEquipment.setMountStatus(1);
//                sysStationEquipment.setOperateBy(userId);
//                sysStationEquipment.setBindTime(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
//                sysStationEquipments.add(sysStationEquipment);
//                //设备绑定订单
//                EquipmentBO sysOrderEquipment = new EquipmentBO();
//                sysOrderEquipment.setOrderId(orderId);
//                sysOrderEquipment.setStationId(sysStation.getStationId());
//                sysOrderEquipment.setEquipmentId(sysEquipment.getEquipmentId());
//                sysOrderEquipment.setCreateBy(userId);
//                sysOrderEquipments.add(sysOrderEquipment);
//            }
//            //对设备进行校验
//            List<String> eqIds = new ArrayList<>();
//            if (sysEquipments.size() > 0) {
//                AjaxResult ajaxResult = equipmentVerifyExistence(sysEquipments, eqIds, orderId);
//                if (!StringUtils.isEmpty(ajaxResult)) {
//                    return ajaxResult;
//                }
//            }
//            //对监测点进行校验
//            if (stations.size() > 0) {
//                List<String> Ids = new ArrayList<>();
//                AjaxResult ajaxResult = stationVerifyExistence(stations, Ids, orderId);
//                if (!StringUtils.isEmpty(ajaxResult)) {
//                    return ajaxResult;
//                }
//            }
//            //验证导入设备是否已经绑定设备
//            if (sysStationEquipments.size() > 0) {
//                AjaxResult ajaxResult = checkStationEquipment(sysStationEquipments);
//                if (!StringUtils.isEmpty(ajaxResult)) {
//                    return ajaxResult;
//                }
//            }
//            //添加设备
//            baseMapper.insertEquipments(sysEquipments);
//            //添加监测点
//            sysStationMapper.insertStations(stations);
//            //监测点绑设备及设备绑定订单
//            relieveBuildling(sysStationEquipments, sysOrderEquipments, orderId, eqIds);
//        }
//        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
//    }

    /**
     * 插入省市区
     */
    private void fillData(Cell cell1, Cell cell2, Cell cell3, SysStation sysStation, List<SysDomain> proList, List<SysDomain> cityList, List<SysDomain> distList) {
        // 此处进行赋值
        // wwPollutionsRepo.setId(row.getCell(0).toString());//省
        String proName = ExcelUtil.getCellStringValue(cell1);
        String cityName = ExcelUtil.getCellStringValue(cell2);
        String distName = ExcelUtil.getCellStringValue(cell3);
        if (proName != null && !"".equals(proName)) {
            Long proid = null;
            for (SysDomain pro : proList) {
                if (pro.getDomainName().equalsIgnoreCase(proName.trim())) {
                    proid = pro.getId();
                    sysStation.setPro(Integer.parseInt(StringUtil.objectString(proid)));
                    break;
                }
            }
            if (proid != null && cityName != null) {
                Long cityId = null;
                for (SysDomain city : cityList) {
                    if (city.getDomainName().equalsIgnoreCase(cityName.trim())
                            && proid.equals(city.getParentId())) {
                        cityId = city.getId();
                        sysStation.setCity(Integer.parseInt(StringUtil.objectString(cityId)));
                        break;
                    }
                }
                if (distName != null && cityId != null) {
                    for (SysDomain dist : distList) {
                        if (dist.getDomainName().equalsIgnoreCase(distName.trim())
                                && cityId.equals(dist.getParentId())) {
                            sysStation.setDistrict(Integer.parseInt(String.valueOf(dist.getId())));
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 从设备池批量导入
     *
     * @param file
     * @param orderId
     * @param userId
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult equipmentPoolExcel(MultipartFile file, String orderId, String userId) throws IOException, InvalidFormatException {
        InputStream in = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(in);
        if (in != null) {
            in.close();
        }
        if (workbook != null) {
            // 遍历每个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
            // 遍历每一行
            EquipmentDTO equipmentDTO = new EquipmentDTO();
            //整理设备编号
            for (int r = 1; r < rowCount; r++) {
                Row row = sheet.getRow(r);
                String value = ExcelUtil.getCellStringValue(row.getCell(0));
                if (!StringUtils.isEmpty(value)) {
                    if (equipmentDTO.getEquipmentIds().contains(value)) {
                        return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + value + "重复");
                    }
                    equipmentDTO.getEquipmentIds().add(value);
                }
            }
            //订单编号
            equipmentDTO.setOrderId(orderId);
            List<String> equipmentIds = equipmentDTO.getEquipmentIds();
            if (equipmentIds.size() == 0) {
                return new AjaxResult(WamingConstant.FAILURE, "请填写导入的设备编号");
            }
            //验证设备是否绑定其他订单
            List<String> count = sysOrderEquipmentMapper.verifyEquipmentOrderId(orderId, equipmentIds, null);
            if (count.size() > 0) {
                String equipmenIdJson = StringUtil.listToString(count);
                return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "不存在或不符合移入条件。");
            }
            List<String> ids = baseMapper.findStationIsDelete(equipmentIds);
            if (ids.size() > 0) {
                String equipmenIdJson = StringUtil.listToString(ids);
                return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "不存在或不符合移入条件。");
            }
            //查询绑定的监测点
            List<EquipmentBO> list = baseMapper.findStationEquipment(equipmentDTO);
            //验证导入到设备编号是否都存在
            if (equipmentIds.size() != list.size()) {
                for (EquipmentBO equipmentBO : list) {
                    if (equipmentIds.contains(equipmentBO.getEquipmentId())) {
                        equipmentIds.remove(equipmentBO.getEquipmentId());
                    }
                }
                String equipmenIdJson = StringUtil.listToString(equipmentIds);
                return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "不存在或不符合移入条件。");
            }
            for (EquipmentBO equipmentBO : list) {
                equipmentBO.setCreateBy(userId);
            }
            //验证设备是否已绑定该订单
            List<SysStationEquipment> equipmentBOs = sysOrderEquipmentMapper.findEquipmentsByOrderId(orderId, equipmentIds);
            if (equipmentBOs.size() > 0) {
                List<String> equipmenIds = new ArrayList<>();
                equipmentBOs.stream().forEach(it -> {
                    equipmenIds.add(it.getEquipmentId());
                });
                String equipmenIdJson = StringUtil.listToString(equipmenIds);
                return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "不存在或不符合移入条件");
            }
            //删除设备，避免重复
            sysOrderEquipmentMapper.deleteEquipmentsByStationIds(orderId, list);
            //绑定设备
            sysOrderEquipmentMapper.orderToEquipment(list);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "从设备池批量移入订单成功");
    }

    /**
     * 设备导入
     *
     * @param file
     * @param orderId
     * @param userId
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult equipmentExcel(MultipartFile file, String orderId, String userId) throws IOException, InvalidFormatException {
        InputStream in = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(in);
        if (in != null) {
            in.close();
        }
        if (workbook != null) {
            // 遍历每个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
            // 遍历每一行
            List<SysEquipment> sysEquipments = new ArrayList<>();
            List<String> equipmentIds = new ArrayList<>();
            List<SysStation> stations = new ArrayList<>();
            List<String> stationIds = new ArrayList<>();
            List<SysStationEquipment> sysStationEquipments = new ArrayList<>();
            List<EquipmentBO> sysOrderEquipments = new ArrayList<>();
            for (int r = 1; r < rowCount; r++) {
                Row row = sheet.getRow(r);
                /*组装设备*/
                AjaxResult ajaxResult = setSysEquipment(row, r, userId);
                if (ajaxResult.getErroCode() != WamingConstant.SUCCESS) {
                    return ajaxResult;
                }
                SysEquipment sysEquipment = (SysEquipment) ajaxResult.getResult();
                if (equipmentIds.contains(sysEquipment.getEquipmentId())) {
                    return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + sysEquipment.getEquipmentId() + "重复");
                }
                equipmentIds.add(sysEquipment.getEquipmentId());
                sysEquipments.add(sysEquipment);
                //监测点不为空则绑定设备与监测点
                String stationId = ExcelUtil.getCellStringValue(row.getCell(14));
                if (!StringUtils.isEmpty(stationId)) {
                    if (stationIds.contains(stationId)) {
                        return new AjaxResult(WamingConstant.FAILURE, "导入的监测点编号" + stationId + "重复");
                    }
                    stationIds.add(stationId);
                    SysStationEquipment sysStationEquipment = new SysStationEquipment();
                    sysStationEquipment.setStationId(stationId);
                    sysStationEquipment.setEquipmentId(sysEquipment.getEquipmentId());
                    sysStationEquipment.setMountStatus(1);
                    sysStationEquipment.setOperateBy(userId);
                    sysStationEquipment.setBindTime(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
                    sysStationEquipments.add(sysStationEquipment);
                    String status = ExcelUtil.getCellStringValue(row.getCell(15));
                    /*监测点信息*/
                    if (!StringUtils.isEmpty(status)) {
                        SysStation sysStation = new SysStation();
                        sysStation.setStationId(stationId);
                        int statusValue = stationStatus(status);
                        if (statusValue == -1) {
                            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第16列监测点状态错误！", null);
                        }
                        sysStation.setStatus(statusValue);
                        stations.add(sysStation);
                    }
                }
                //订单绑定监测点
                EquipmentBO sysOrderEquipment = new EquipmentBO();
                sysOrderEquipment.setOrderId(orderId);
                if (!StringUtils.isEmpty(stationId)) {
                    sysOrderEquipment.setStationId(stationId);
                }
                sysOrderEquipment.setEquipmentId(sysEquipment.getEquipmentId());
                sysOrderEquipment.setCreateBy(userId);
                sysOrderEquipments.add(sysOrderEquipment);
            }
            if (sysStationEquipments.size() > 0) {
                List<String> Ids = new ArrayList<>();
                sysStationEquipments.stream().forEach(it -> {
                    Ids.add(it.getStationId());
                });
                List<String> stationsIds = sysStationMapper.findStations(Ids);
                if (Ids.size() != stationsIds.size()) {
                    for (String stationsId : stationsIds) {
                        if (Ids.contains(stationsId)) {
                            Ids.remove(stationsId);
                        }
                    }
                    String equipmenIdJson = StringUtil.listToString(Ids);
                    return new AjaxResult(WamingConstant.FAILURE, "监测点" + equipmenIdJson + "不存在");
                }
            }
            //添加设备
            List<String> eqIds = new ArrayList<>();
            if (sysEquipments.size() > 0) {
                AjaxResult ajaxResult = equipmentVerifyExistence(sysEquipments, eqIds, orderId);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //验证导入设备是否已经绑定设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = checkStationEquipment(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //修改监测点状态
            if (stations.size() > 0) {
                for (SysStation sysStation : stations) {
                    sysStationMapper.updateStationByStationId(sysStation.getStationId(), sysStation.getStatus());
                }
            }
            //添加设备
            baseMapper.insertEquipments(sysEquipments);
            //设备绑定监测点、订单绑定设备
            relieveBuildling(sysStationEquipments, sysOrderEquipments, orderId, eqIds);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
    }

//    /**
//     * 网格化监测点导入
//     *
//     * @param file
//     * @param orderId
//     * @param userId
//     * @return
//     * @throws IOException
//     * @throws InvalidFormatException
//     */
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public AjaxResult stationExcel(MultipartFile file, String orderId, String userId) throws IOException, InvalidFormatException {
//        List<SysDomain> proList = sysDomainMapper.getAllDomainDTOById(PROID);
//        List<SysDomain> cityList = sysDomainMapper.getAllDomainDTOById(CITYID);
//        List<SysDomain> distList = sysDomainMapper.getAllDomainDTOById(DISTID);
//        TypeConfigDTO typeConfigDTO = setTypeConfig();
//        InputStream in = file.getInputStream();
//        Workbook workbook = WorkbookFactory.create(in);
//        if (in != null) {
//            in.close();
//        }
//        if (workbook != null) {
//            // 遍历每个Sheet
//            Sheet sheet = workbook.getSheetAt(0);
//            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
//            // 遍历每一行
//            List<SysStation> stations = new ArrayList<>();
//            List<String> stationIds = new ArrayList<>();
//            List<SysEquipment> equipments = new ArrayList<>();
//            List<String> equipmentIds = new ArrayList<>();
//            List<SysStationEquipment> sysStationEquipments = new ArrayList<>();
//            List<EquipmentBO> sysOrderEquipments = new ArrayList<>();
//            for (int r = 1; r < rowCount; r++) {
//                Row row = sheet.getRow(r);
//                /*监测点信息*/
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第1列监测点编号不能为空！", null);
//                }
//                SysStation sysStation = new SysStation();
//                sysStation.setStationId(ExcelUtil.getCellStringValue(row.getCell(0)));
//                if (stationIds.contains(sysStation.getStationId())) {
//                    return new AjaxResult(WamingConstant.FAILURE, "导入的监测点编号" + sysStation.getStationId() + "重复");
//                }
//                stationIds.add(sysStation.getStationId());
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(1)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第2列监测点名称不能为空！", null);
//                }
//                //监测点名称
//                sysStation.setStationName(ExcelUtil.getCellStringValue(row.getCell(1)));
//                //监测点种类
//                String equipmentType = ExcelUtil.getCellStringValue(row.getCell(2));
//                if (StringUtils.isEmpty(equipmentType)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第3列监测点种类不能为空！", null);
//                }
//                String stType = ExcelUtil.getCellStringValue(row.getCell(3));
//                if (StringUtils.isEmpty(stType)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第4列监测点类型不能为空！", null);
//                }
//                //监测点类型
//                matchingType(equipmentType, stType, sysStation, typeConfigDTO);
//                String value = ExcelUtil.getCellStringValue(row.getCell(4));
//                if (StringUtils.isEmpty(value)) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列监测点状态不能为空！", null);
//                }
//                //监测点状态
//                int statusValue = stationStatus(value);
//                if (statusValue == -1) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列监测点状态错误！", null);
//                }
//                sysStation.setStatus(statusValue);
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(5)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第6列省份不能为空！", null);
//                }
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(6)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第7列城市不能为空！", null);
//                }
//                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(7)))) {
//                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第8列区县不能为空！", null);
//                }
//                //省市区
//                fillData(row.getCell(5), row.getCell(6), row.getCell(7), sysStation, proList, cityList, distList);
//                //地址
//                sysStation.setAddr(ExcelUtil.getCellStringValue(row.getCell(8)));
//                //gps纬度
//                sysStation.setLatReal(new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(9))));
//                //gps经度
//                sysStation.setLngReal(new BigDecimal(ExcelUtil.getCellStringValue(row.getCell(10))));
//                //杆号
//                sysStation.setPoleId(ExcelUtil.getCellStringValue(row.getCell(11)));
//                //电表号
//                sysStation.setAmmeterNo(ExcelUtil.getCellStringValue(row.getCell(12)));
//                sysStation.setCreateBy(userId);
//                sysStation.setCreateDt(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
//                stations.add(sysStation);
//                //设备绑定监测点
//                String equipmentId = StringUtil.objectString(row.getCell(13));
//                if (!StringUtils.isEmpty(equipmentId)) {
//                    if (equipmentIds.contains(equipmentId)) {
//                        return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + equipmentId + "重复");
//                    }
//                    equipmentIds.add(equipmentId);
//                    SysStationEquipment sysStationEquipment = new SysStationEquipment();
//                    sysStationEquipment.setStationId(sysStation.getStationId());
//                    sysStationEquipment.setEquipmentId(equipmentId);
//                    sysStationEquipment.setMountStatus(1);
//                    sysStationEquipment.setOperateBy(userId);
//                    sysStationEquipment.setBindTime(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
//                    sysStationEquipments.add(sysStationEquipment);
//                    /*设备信息*/
//                    String status = ExcelUtil.getCellStringValue(row.getCell(14));
//                    if (!StringUtils.isEmpty(status)) {
//                        SysEquipment sysEquipment = new SysEquipment();
//                        sysEquipment.setEquipmentId(equipmentId);
//                        int stationStatusvalue = stationStatus(status);
//                        if (stationStatusvalue == -1) {
//                            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第15列监测点状态错误！", null);
//                        }
//                        sysEquipment.setStatus(stationStatusvalue);
//                        equipments.add(sysEquipment);
//                    }
//                }
//                //订单绑定设备信息
//                EquipmentBO sysOrderEquipment = new EquipmentBO();
//                sysOrderEquipment.setOrderId(orderId);
//                sysOrderEquipment.setStationId(sysStation.getStationId());
//                if (!StringUtils.isEmpty(equipmentId)) {
//                    sysOrderEquipment.setEquipmentId(equipmentId);
//                }
//                sysOrderEquipment.setCreateBy(userId);
//                sysOrderEquipments.add(sysOrderEquipment);
//            }
//            //验证设备
//            if (sysStationEquipments.size() > 0) {
//                AjaxResult ajaxResult = updateEquipmentStatus(sysStationEquipments);
//                if (!StringUtils.isEmpty(ajaxResult)) {
//                    return ajaxResult;
//                }
//            }
//            //添加监测点
//            List<String> Ids = new ArrayList<>();
//            if (stations.size() > 0) {
//                AjaxResult ajaxResult = stationVerifyExistence(stations, Ids, orderId);
//                if (!StringUtils.isEmpty(ajaxResult)) {
//                    return ajaxResult;
//                }
//            }
//            //验证导入设备是否已经绑定设备
//            if (sysStationEquipments.size() > 0) {
//                AjaxResult ajaxResult = checkStationEquipment(sysStationEquipments);
//                if (!StringUtils.isEmpty(ajaxResult)) {
//                    return ajaxResult;
//                }
//            }
//            //修改设备状态
//            if (equipments.size() > 0) {
//                for (SysEquipment sysEquipment : equipments) {
//                    baseMapper.updateEquipmentByEquipmentId(sysEquipment.getEquipmentId(), sysEquipment.getStatus());
//                }
//            }
//            //添加监测点
//            sysStationMapper.insertStations(stations);
//            //绑定设备和监测点，绑定订单和设备
//            relieveBuildling(sysStationEquipments, sysOrderEquipments, orderId, Ids);
//        }
//        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
//    }

    /**
     * 健康空气设备监测点导入
     *
     * @param file
     * @param orderId
     * @param userId
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult equipmentStationExcelJKKQ(MultipartFile file, String orderId, String userId) throws IOException, InvalidFormatException {
        List<SysStationMoDTO> stationMos = sysStationGroupMapper.findStationMo();
        List<SysStationMoDTO> mos = setMoMap(stationMos);
        InputStream in = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(in);
        if (in != null) {
            in.close();
        }
        if (workbook != null) {
            // 遍历每个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
            // 遍历每一行
            List<SysEquipment> sysEquipments = new ArrayList<>();
            List<String> equipmentIds = new ArrayList<>();
            List<SysStation> stations = new ArrayList<>();
            List<String> stationIds = new ArrayList<>();
            List<SysStationEquipment> sysStationEquipments = new ArrayList<>();
            List<EquipmentBO> sysOrderEquipments = new ArrayList<>();
            for (int r = 1; r < rowCount; r++) {
                Row row = sheet.getRow(r);
                /*设备数据*/
                AjaxResult ajaxResult = setSysEquipment(row, r, userId);
                if (ajaxResult.getErroCode() != WamingConstant.SUCCESS) {
                    return ajaxResult;
                }
                SysEquipment sysEquipment = (SysEquipment) ajaxResult.getResult();
                if (equipmentIds.contains(sysEquipment.getEquipmentId())) {
                    return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + sysEquipment.getEquipmentId() + "重复");
                }
                equipmentIds.add(sysEquipment.getEquipmentId());
                sysEquipments.add(sysEquipment);
                /*监测点数据*/
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(14)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第15列监测点编号不能为空！", null);
                }
                SysStation sysStation = new SysStation();
                sysStation.setEquipmentId(sysEquipment.getEquipmentId());
                //监测点编号
                sysStation.setStationId(ExcelUtil.getCellStringValue(row.getCell(14)));
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(15)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第16列监测点名称不能为空！", null);
                }
                //监测点名称
                sysStation.setStationName(ExcelUtil.getCellStringValue(row.getCell(15)));
                //监测点种类
                String sTechType = ExcelUtil.getCellStringValue(row.getCell(16));
                if (StringUtils.isEmpty(sTechType)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第17列监测点种类不能为空！", null);
                }
                //监测点类型及种类处理
                matchingType(sTechType, null, sysStation, null);
                String value = ExcelUtil.getCellStringValue(row.getCell(17));
                if (StringUtils.isEmpty(value)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第18列监测点状态不能为空！", null);
                }
                //监测点状态
                int stationStatus = stationStatus(value);
                if (stationStatus == -1) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第18列监测点状态错误！", null);
                }
                sysStation.setStatus(stationStatus);
                //空间
                if (!StringUtils.isEmpty(row.getCell(18))) {
                    String space = ExcelUtil.getCellStringValue(row.getCell(18));
                    String[] split = space.split("/");
                    String moId = setStationMoId(split, mos, 0, "");
                    if (StringUtils.isEmpty(moId)) {
                        return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第19列空间填写错误！", null);
                    }
                    sysStation.setMoId(moId);
                }
                sysStation.setCreateBy(userId);
                sysStation.setCreateDt(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
                if (stationIds.contains(sysStation.getStationId())) {
                    return new AjaxResult(WamingConstant.FAILURE, "导入的监测点编号" + sysStation.getStationId() + "重复");
                }
                stationIds.add(sysStation.getStationId());
                stations.add(sysStation);
                //设备监测点绑定信息
                SysStationEquipment sysStationEquipment = new SysStationEquipment();
                sysStationEquipment.setStationId(sysStation.getStationId());
                sysStationEquipment.setEquipmentId(sysEquipment.getEquipmentId());
                sysStationEquipment.setMountStatus(1);
                sysStationEquipment.setOperateBy(userId);
                sysStationEquipment.setBindTime(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
                sysStationEquipments.add(sysStationEquipment);
                //订单绑定设备
                EquipmentBO sysOrderEquipment = new EquipmentBO();
                sysOrderEquipment.setOrderId(orderId);
                sysOrderEquipment.setStationId(sysStation.getStationId());
                sysOrderEquipment.setEquipmentId(sysEquipment.getEquipmentId());
                sysOrderEquipment.setCreateBy(userId);
                sysOrderEquipments.add(sysOrderEquipment);
            }
            //校验设备
            List<String> eqIds = new ArrayList<>();
            if (sysEquipments.size() > 0) {
                AjaxResult ajaxResult = equipmentVerifyExistence(sysEquipments, eqIds, orderId);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //校验监测点
            if (stations.size() > 0) {
                List<String> Ids = new ArrayList<>();
                AjaxResult ajaxResult = stationVerifyExistence(stations, Ids, orderId);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //验证导入设备是否已经绑定设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = checkStationEquipment(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //添加设备
            baseMapper.insertEquipments(sysEquipments);
            //添加监测点
            sysStationMapper.insertStations(stations);
            //绑定设备和监测点，绑定订单和设备
            relieveBuildling(sysStationEquipments, sysOrderEquipments, orderId, eqIds);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
    }

    public List<SysStationMoDTO> setMoMap(List<SysStationMoDTO> stationMos) {
        //按父菜单分类
        Map<String, List<SysStationMoDTO>> funcMap =
                stationMos.stream().filter(it -> it.getParentId() != null).collect(Collectors.groupingBy(SysStationMoDTO::getParentId));
        //有子菜单的设置子菜单
        stationMos.stream().filter(it -> funcMap.keySet().contains(it.getId())).forEach(it -> {
            it.setChildrenMoDTOs(funcMap.get(it.getId()).stream().collect(Collectors.toList()));
        });
        //将第一级菜单返回
        List<SysStationMoDTO> menuDTOList =
                stationMos.stream().filter(it -> StringUtils.isEmpty(it.getParentId())).collect(Collectors.toList());
        return menuDTOList;
    }

    public String setStationMoId(String[] split, List<SysStationMoDTO> stationMos, int num, String moId) {
        if (num >= split.length) {
            return moId;
        }
        for (SysStationMoDTO it : stationMos) {
            if (split[num].equals(it.getCapation())) {
                moId = setStationMoId(split, it.getChildrenMoDTOs(), num + 1, it.getId());
                break;
            }
        }
        return moId;
    }

    /**
     * 健康空气监测点导入
     *
     * @param file
     * @param orderId
     * @param userId
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult stationExcelJKKQ(MultipartFile file, String orderId, String userId) throws IOException, InvalidFormatException {
        List<SysStationMoDTO> stationMos = sysStationGroupMapper.findStationMo();
        List<SysStationMoDTO> mos = setMoMap(stationMos);
        InputStream in = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(in);
        if (in != null) {
            in.close();
        }
        if (workbook != null) {
            // 遍历每个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
            // 遍历每一行
            List<SysStation> stations = new ArrayList<>();
            List<String> stationIds = new ArrayList<>();
            List<SysEquipment> sysEquipments = new ArrayList<>();
            List<String> equipmentIds = new ArrayList<>();
            List<SysStationEquipment> sysStationEquipments = new ArrayList<>();
            List<EquipmentBO> sysOrderEquipments = new ArrayList<>();
            for (int r = 1; r < rowCount; r++) {
                Row row = sheet.getRow(r);
                /*监测点信息*/
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第1列监测点编号不能为空！", null);
                }
                SysStation sysStation = new SysStation();
                //监测点编号
                sysStation.setStationId(ExcelUtil.getCellStringValue(row.getCell(0)));
                if (stationIds.contains(sysStation.getStationId())) {
                    return new AjaxResult(WamingConstant.FAILURE, "导入的监测点编号" + sysStation.getStationId() + "重复");
                }
                stationIds.add(sysStation.getStationId());
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(1)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第2列监测点名称不能为空！", null);
                }
                //监测点名称
                sysStation.setStationName(ExcelUtil.getCellStringValue(row.getCell(1)));
                //监测点种类
                String sTechType = ExcelUtil.getCellStringValue(row.getCell(2));
                if (StringUtils.isEmpty(sTechType)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第3列监测点种类不能为空！", null);
                }
                //监测点类型及种类处理
                matchingType(sTechType, null, sysStation, null);
                String value = ExcelUtil.getCellStringValue(row.getCell(3));
                if (StringUtils.isEmpty(value)) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第4列监测点状态不能为空！", null);
                }
                int statusValue = stationStatus(value);
                if (statusValue == -1) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第4列监测点状态错误！", null);
                }
                //监测点状态
                sysStation.setStatus(statusValue);
                //空间
                if (!StringUtils.isEmpty(row.getCell(4))) {
                    String space = ExcelUtil.getCellStringValue(row.getCell(4));
                    String[] split = space.split("/");
                    String moId = setStationMoId(split, mos, 0, "");
                    if (StringUtils.isEmpty(moId)) {
                        return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列空间填写错误！", null);
                    }
                    sysStation.setMoId(moId);
                }
                sysStation.setCreateBy(userId);
                sysStation.setCreateDt(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
                stations.add(sysStation);
                //设备绑定监测点
                String equipmentId = ExcelUtil.getCellStringValue(row.getCell(5));
                if (!StringUtils.isEmpty(equipmentId)) {
                    if (equipmentIds.contains(equipmentId)) {
                        return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + equipmentId + "重复");
                    }
                    equipmentIds.add(equipmentId);
                    SysStationEquipment sysStationEquipment = new SysStationEquipment();
                    sysStationEquipment.setStationId(sysStation.getStationId());
                    sysStationEquipment.setEquipmentId(equipmentId);
                    sysStationEquipment.setMountStatus(1);
                    sysStationEquipment.setOperateBy(userId);
                    sysStationEquipment.setBindTime(com.qingcloud.adminbackend.utils.DateUtil.getDateTime(new Date()));
                    sysStationEquipments.add(sysStationEquipment);
                    /*设备信息*/
                    String status = ExcelUtil.getCellStringValue(row.getCell(6));
                    if (!StringUtils.isEmpty(status)) {
                        SysEquipment sysEquipment = new SysEquipment();
                        sysEquipment.setEquipmentId(equipmentId);
                        int status1 = equipmentStatus(status);
                        if (status1 == -1) {
                            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第7列设备状态错误！", null);
                        }
                        sysEquipment.setStatus(status1);
                        sysEquipments.add(sysEquipment);
                    }
                }
                //订单绑定设备
                EquipmentBO sysOrderEquipment = new EquipmentBO();
                sysOrderEquipment.setOrderId(orderId);
                sysOrderEquipment.setStationId(sysStation.getStationId());
                if (!StringUtils.isEmpty(equipmentId)) {
                    sysOrderEquipment.setEquipmentId(equipmentId);
                }
                sysOrderEquipment.setCreateBy(userId);
                sysOrderEquipments.add(sysOrderEquipment);
            }
            //验证设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = updateEquipmentStatus(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //添加监测点
            List<String> Ids = new ArrayList<>();
            if (stations.size() > 0) {
                AjaxResult ajaxResult = stationVerifyExistence(stations, Ids, orderId);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //验证导入设备是否已经绑定设备
            if (sysStationEquipments.size() > 0) {
                AjaxResult ajaxResult = checkStationEquipment(sysStationEquipments);
                if (!StringUtils.isEmpty(ajaxResult)) {
                    return ajaxResult;
                }
            }
            //修改设备状态
            if (sysEquipments.size() > 0) {
                for (SysEquipment sysEquipment : sysEquipments) {
                    baseMapper.updateEquipmentByEquipmentId(sysEquipment.getEquipmentId(), sysEquipment.getStatus());
                }
            }
            //添加监测点
            sysStationMapper.insertStations(stations);
            //绑定设备和监测点，绑定订单和监测点
            relieveBuildling(sysStationEquipments, sysOrderEquipments, orderId, Ids);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
    }


    /**
     * 产品系列
     *
     * @param productSeries
     * @return
     */
    public String setproductSeries(String productSeries) {
        if ("室内".equals(productSeries)) {
            return "0";
        }
        if ("微站".equals(productSeries)) {
            return "1";
        }
        if ("便携式".equals(productSeries)) {
            return "2";
        }
        if ("无人机".equals(productSeries)) {
            return "3";
        }
        return null;
    }

    /**
     * 设备信息
     *
     * @param row
     * @param r
     * @param userId
     * @return
     */
    public AjaxResult setSysEquipment(Row row, int r, String userId) {
/*//        SysEquipment sysEquipment = new SysEquipment();
//        if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
//            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第1列设备编号不能为空！", null);
//        }
//        sysEquipment.setId(UUID.randomUUID().toString().replace("-", ""));
//        sysEquipment.setEquipmentId(ExcelUtil.getCellStringValue(row.getCell(0)));
//
//        if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(1)))) {
//            String productType = setproductSeries(ExcelUtil.getCellStringValue(row.getCell(1)));
//            if (StringUtils.isEmpty(productType)) {
//                return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第2列产品系列不正确！", null);
//            }
//            //产品系列
//            sysEquipment.setProductType(productType);
//        }
//        //产品型号
//        sysEquipment.setProductModel(ExcelUtil.getCellStringValue(row.getCell(2)));
//        //监测因子
//        sysEquipment.setMonitorFactor(ExcelUtil.getCellStringValue(row.getCell(3)));
//        //设备状态条件处理待调整
//        String value = ExcelUtil.getCellStringValue(row.getCell(4));
//        if (StringUtils.isEmpty(value)) {
//            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列设备状态不能为空！", null);
//        }
//        int statusValue = equipmentStatus(value);
//        if (statusValue == -1) {
//            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第5列设备状态错误！", null);
//        }
//        sysEquipment.setStatus(statusValue);
//        //设备类型条件处理待调整
//        String value1 = ExcelUtil.getCellStringValue(row.getCell(5));
//        if (StringUtils.isEmpty(value1)) {
//            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第6列设备类型不能为空！", null);
//        }
//        int stechTypeValue = equipmentStechType(value1);
//        if (stechTypeValue == -1) {
//            return new AjaxResult(WamingConstant.FAILURE, "解析第" + r + "行第6列设备类型错误！", null);
//        }
//        sysEquipment.setSTechType(stechTypeValue);
//        //物联网卡号
//        sysEquipment.setInternetofthingsCode(ExcelUtil.getCellStringValue(row.getCell(6)));
//        //采集间隔
//        sysEquipment.setCollectInternel(ExcelUtil.getCellStringValue(row.getCell(7)));
//        //上传间隔
//        sysEquipment.setUploadInternel(ExcelUtil.getCellStringValue(row.getCell(8)));
//        //固件类型
//        sysEquipment.setFirmwareType(ExcelUtil.getCellStringValue(row.getCell(9)));
//        //供应商
//        sysEquipment.setSupplier(ExcelUtil.getCellStringValue(row.getCell(10)));
//        //生产厂家
//        sysEquipment.setManufacturer(ExcelUtil.getCellStringValue(row.getCell(11)));
//        //协议类型
//        sysEquipment.setProtocolType(ExcelUtil.getCellStringValue(row.getCell(12)));
//        //出厂时间
//        if (!StringUtils.isEmpty(row.getCell(13))) {
//            sysEquipment.setFactoryTime(ExcelUtil.getCellStringValue(row.getCell(13)));
//        }
//        sysEquipment.setCreateBy(userId);
//        sysEquipment.setCreateDt(DateUtil.getDateTime(new Date()));
        //  return new AjaxResult(WamingConstant.SUCCESS, "", sysEquipment);*/
        return new AjaxResult(WamingConstant.SUCCESS, "", "");
    }

    /**
     * 验证设备是否已经存在及插入设备
     *
     * @param sysEquipments
     * @param eqIds
     * @return
     */
    public AjaxResult equipmentVerifyExistence(List<SysEquipment> sysEquipments, List<String> eqIds, String orderId) {
        sysEquipments.stream().forEach(it -> {
            eqIds.add(it.getEquipmentId());
        });
        //验证设备是否绑定其他订单
        List<String> count = sysOrderEquipmentMapper.verifyEquipmentOrderId(orderId, eqIds, null);
        if (count.size() > 0) {
            String equipmenIdJson = StringUtil.listToString(count);
            return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "已绑定其他订单");
        }
        List<String> equipmentIds = baseMapper.findEquipments(eqIds);
        if (equipmentIds.size() > 0) {
            String equipmenIdJson = StringUtil.listToString(equipmentIds);
            return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "已经存在");
        }
        return null;
    }

    /**
     * 验证监测点是否已经存在及插入监测点
     *
     * @param sysStations
     * @return
     */
    public AjaxResult stationVerifyExistence(List<SysStation> sysStations, List<String> Ids, String orderId) {
        sysStations.stream().forEach(it -> {
            Ids.add(it.getStationId());
        });
        //验证设备是否绑定其他订单
        List<String> count = sysOrderEquipmentMapper.verifyEquipmentOrderId(orderId, null, Ids);
        if (count.size() > 0) {
            String equipmenIdJson = StringUtil.listToString(count);
            return new AjaxResult(WamingConstant.FAILURE, "监测点" + equipmenIdJson + "已绑定其他订单");
        }
        List<String> equipmentIds = sysStationMapper.findStations(Ids);
        if (equipmentIds.size() > 0) {
            String equipmenIdJson = StringUtil.listToString(equipmentIds);
            return new AjaxResult(WamingConstant.FAILURE, "监测点" + equipmenIdJson + "已经存在");
        }
        return null;
    }

    /**
     * 绑定设备和监测点，绑定订单和监测点
     *
     * @param sysStationEquipments
     * @param sysOrderEquipments
     * @param orderId
     * @param eqIds
     */
    public void relieveBuildling(List<SysStationEquipment> sysStationEquipments, List<EquipmentBO> sysOrderEquipments, String orderId, List<String> eqIds) {
        if (sysStationEquipments.size() > 0) {
            //批量解除设备与检测的绑定关系
            sysStationEquipmentMapper.deleteStationEquipments(sysStationEquipments);
            //建立设备与检测的绑定关系
            sysStationEquipmentMapper.insertStationEquipments(sysStationEquipments);
            Map<String, String> stationMap = new HashMap<>();
            Map<String, String> equipmentMap = new HashMap<>();
            sysStationEquipments.stream().forEach(it -> {
                stationMap.put(it.getStationId(), it.getEquipmentId());
                equipmentMap.put(it.getEquipmentId(), it.getStationId());
            });
            //查询设备与设备组绑定关系
            List<SysStationGroupEquipment> list = sysStationGroupEquipmentMapper.findStationGroupEquipment(sysStationEquipments);
            if (list.size() > 0) {
                //删除设备与设备组绑定关系
                sysStationGroupEquipmentMapper.deleteStationGroupEquipment(list);
                list.stream().forEach(it -> {
                    if (StringUtils.isEmpty(it.getEquipmentId())) {
                        it.setEquipmentId(stationMap.get(it.getStationId()));
                    }
                    if (StringUtils.isEmpty(it.getStationId())) {
                        it.setStationId(equipmentMap.get(it.getEquipmentId()));
                    }
                });
                //添加设备与设备组绑定关系
                sysStationGroupEquipmentMapper.insertStationGroupEquipment(list);
            }
        }
        if (sysOrderEquipments.size() > 0) {
            //删除订单已经绑定的设备，避免重复绑定
            sysOrderEquipmentMapper.deleteEquipmentsByStationIds(orderId, sysOrderEquipments);
            //添加订单和设备的绑定
            sysOrderEquipmentMapper.orderToEquipment(sysOrderEquipments);
        }
    }

    public AjaxResult checkStationEquipment(List<SysStationEquipment> sysStationEquipments) {
        //验证设备与监测的绑定关系
        List<SysStationEquipment> stationEquipments = sysStationEquipmentMapper.findStationEquipments(sysStationEquipments);
        if (stationEquipments.size() > 0) {
            String equipmenIdJson = StringUtil.objectToString(stationEquipments);
            return new AjaxResult(WamingConstant.FAILURE, equipmenIdJson + "已经绑定");
        }
        return null;
    }

    /**
     * 站点状态
     *
     * @param status
     * @return
     */
    public int stationStatus(String status) {
        //(2正常、1下线、0维护中、3未激活)
        if ("正常".equals(status)) {
            return 2;
        }
        if ("下线".equals(status)) {
            return 1;
        }
        if ("休眠".equals(status)) {
            return 0;
        }
        if ("未激活".equals(status)) {
            return 3;
        }
        return -1;
    }

    /**
     * 设备状态
     *
     * @param status
     * @return
     */
    public int equipmentStatus(String status) {
        //(3:故障;2正常;1:维修中;0:报废)
        if ("故障".equals(status)) {
            return 3;
        }
        if ("正常".equals(status)) {
            return 2;
        }
        if ("运维中".equals(status)) {
            return 1;
        }
        if ("报废".equals(status)) {
            return 0;
        }
        return -1;
    }

    /**
     * 设备类型
     *
     * @param stechType
     * @return
     */
    public int equipmentStechType(String stechType) {
        //设备类型(6010:6传感器、1010:单传感器、6020:tvoc, 99爬虫源、98考核站、101:扬尘站、、100:其他)
        if ("６传感器".equals(stechType)) {
            return 6010;
        }
        if ("单传感器".equals(stechType)) {
            return 1010;
        }
        if ("TVOC".equals(stechType)) {
            return 6020;
        }
        if ("爬虫源".equals(stechType)) {
            return 99;
        }
        if ("考核站".equals(stechType)) {
            return 98;
        }
        if ("扬尘站".equals(stechType)) {
            return 101;
        }
        if ("噪声".equals(stechType)) {
            return 6030;
        }
        if ("噪声TVOC".equals(stechType)) {
            return 6040;
        }
        if ("其他".equals(stechType)) {
            return 100;
        }
        return -1;
    }

    /**
     * 监测点类型及种类处理
     *
     * @param equipmentType
     * @param stType
     * @param sysStation
     * @param typeConfigDTO
     */
    public void matchingType(String equipmentType, String stType, SysStation sysStation, TypeConfigDTO typeConfigDTO) {
        if (StrUtil.isNotBlank(equipmentType)) {
            //0微站 1便携式 2小型站 3移动站 4考核站 5爬虫站 6扬尘站 7室内监测 8室外监测
            switch (equipmentType) {
                case "微站":
//                    sysStation.setEquipmentType(0);
//                    sysStation.setSTechType(6010);
                    sysStation.setStatus(3);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getMicroTypeMap().get(stType));
                    }
                    break;
                case "便携式":
//                    sysStation.setEquipmentType(1);
//                    sysStation.setSTechType(100);
                    sysStation.setStatus(3);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getYcTypeMap().get(stType));
                    }
                    break;
                case "小型站":
//                    sysStation.setEquipmentType(2);
//                    sysStation.setSTechType(100);
                    sysStation.setStatus(3);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getYcTypeMap().get(stType));
                    }
                    break;
                case "移动站":
//                    sysStation.setEquipmentType(3);
//                    sysStation.setSTechType(100);
                    sysStation.setStatus(3);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getYcTypeMap().get(stType));
                    }
                    break;
                case "考核站":
//                    sysStation.setEquipmentType(4);
//                    sysStation.setSTechType(98);
                    sysStation.setStatus(2);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getKaoheTypeMap().get(stType));
                    }
                    break;
                case "爬虫站":
//                    sysStation.setEquipmentType(5);
//                    sysStation.setSTechType(99);
                    sysStation.setStatus(2);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getCrawlyTypeMap().get(stType));
                    }
                    break;
                case "扬尘站":
//                    sysStation.setEquipmentType(6);
//                    sysStation.setSTechType(101);
                    sysStation.setStatus(2);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getYcTypeMap().get(stType));
                    }
                    break;
                case "室内监测":
//                    sysStation.setEquipmentType(7);
//                    sysStation.setSTechType(100);
                    sysStation.setStatus(3);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getYcTypeMap().get(stType));
                    }
                    break;
                case "室外监测":
//                    sysStation.setEquipmentType(8);
//                    sysStation.setSTechType(100);
                    sysStation.setStatus(3);
                    if (StrUtil.isNotBlank(stType)) {
                        sysStation.setStationType(typeConfigDTO.getYcTypeMap().get(stType));
                    }
                    break;
                default:
                    break;
            }
        }
    }

//    /**
//     * 查询全部监测点种类对应的站点类型
//     *
//     * @return
//     */
//    public TypeConfigDTO setTypeConfig() {
//        TypeConfigDTO typeConfigDTO = new TypeConfigDTO();
//        // 微站下属站点类型
//        List<WwWtypeConfigDTO> microTypeList = typeConfigMapper.findByType(19);
//        // 考核站下属站点类型
//        List<WwWtypeConfigDTO> kaoheTypeList = typeConfigMapper.findByType(21);
//        // 爬虫站下属站点类型
//        List<WwWtypeConfigDTO> crawlyTypeList = typeConfigMapper.findByType(20);
//        // 扬尘站下属站点类型
//        List<WwWtypeConfigDTO> ycTypeList = typeConfigMapper.findByType(26);
//        // 微站下属站点类型map
//        Map<String, Integer> microTypeMap = Maps.newHashMap();
//        // 考核站下属站点类型map
//        Map<String, Integer> kaoheTypeMap = Maps.newHashMap();
//        // 爬虫站下属站点类型map
//        Map<String, Integer> crawlyTypeMap = Maps.newHashMap();
//        // 扬尘站下属站点类型map
//        Map<String, Integer> ycTypeMap = Maps.newHashMap();
//        // 分别放入对应map中
//        if (!StringUtils.isEmpty(microTypeList)) {
//            microTypeList.forEach(each -> {
//                microTypeMap.put(each.getName(), Convert.toInt(each.getCode()));
//            });
//        }
//        if (!StringUtils.isEmpty(kaoheTypeList)) {
//            kaoheTypeList.forEach(each -> {
//                kaoheTypeMap.put(each.getName(), Convert.toInt(each.getCode()));
//            });
//        }
//        if (!StringUtils.isEmpty(crawlyTypeList)) {
//            crawlyTypeList.forEach(each -> {
//                crawlyTypeMap.put(each.getName(), Convert.toInt(each.getCode()));
//            });
//        }
//        if (!StringUtils.isEmpty(ycTypeList)) {
//            ycTypeList.forEach(each -> {
//                ycTypeMap.put(each.getName(), Convert.toInt(each.getCode()));
//            });
//        }
//        typeConfigDTO.setMicroTypeMap(microTypeMap);
//        typeConfigDTO.setKaoheTypeMap(kaoheTypeMap);
//        typeConfigDTO.setYcTypeMap(ycTypeMap);
//        typeConfigDTO.setCrawlyTypeMap(crawlyTypeMap);
//        return typeConfigDTO;
//    }

    /**
     * 批量更新设备状态并验证设备是否存在
     */
    public AjaxResult updateEquipmentStatus(List<SysStationEquipment> sysStationEquipments) {
        List<String> eqIds = new ArrayList<>();
        sysStationEquipments.stream().forEach(it -> {
            eqIds.add(it.getEquipmentId());
        });
        List<String> equipmentIds = baseMapper.findEquipments(eqIds);
        if (eqIds.size() != equipmentIds.size()) {
            for (String equipmentId : equipmentIds) {
                if (eqIds.contains(equipmentId)) {
                    eqIds.remove(equipmentId);
                }
            }
            String equipmenIdJson = StringUtil.listToString(eqIds);
            return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "不存在");
        }
        return null;
    }


    @Override
    public IPage<UnbindEquipmentDTO> findUnbindEquipment(Integer currentPage, Integer perPage, String orderId) {
        Page<UnbindEquipmentDTO> page = new Page<>(currentPage, perPage);
        //该订单下的所有没有绑定的设备
        List<SysOrderEquipment> orderEqs = sysOrderEquipmentMapper.selectByMap(ImmutableMap.of("order_id", orderId));
        if (CollUtil.isEmpty(orderEqs)) {
            return new Page<>();
        }
        List<String> equipmentIds = orderEqs.stream().filter(x -> StrUtil.isBlank(x.getStationId()) && StrUtil.isNotBlank(x.getEquipmentId())).map
                (SysOrderEquipment::getEquipmentId).collect(Collectors.toList());
        if (CollUtil.isEmpty(equipmentIds)) {
            return new Page<>();
        }
        IPage<UnbindEquipmentDTO> unbindEquipment = sysEquipmentMapper.findUnbindEquipment(page, equipmentIds);
        List<SysSensorFactorConfig> sysSensorFactorConfigs = sysSensorFactorConfigMapper.selectByMap(ImmutableMap.of());
        Map<Integer, String> map = sysSensorFactorConfigs.stream().collect(Collectors.toMap(SysSensorFactorConfig::getFactorId,
                SysSensorFactorConfig::getFactorDesc));
        List<SysSensorFactorConfig> sensorFactorConfig = baseService.findSensorFactorConfig();
        List<UnbindEquipmentDTO> records = unbindEquipment.getRecords();
        records.forEach(record -> {
            String chooseIds = record.getFactorIds();
            String desc = "";
            if (StrUtil.isBlank(chooseIds)) {
                //没有传感器，显示应有监测因子
                String sensorFactors = record.getSensorFactors();
                if (StrUtil.isNotBlank(sensorFactors)) {
                    desc = baseService.spellSensorFactorConfig(sensorFactorConfig, sensorFactors);
                }
            } else {
                desc = baseService.spellSensorFactorConfig(sensorFactorConfig, chooseIds);
            }
            record.setSensorContents(baseService.getFactor(map, desc));
        });
        return unbindEquipment;
    }

    @Override
    public IPage<EquipmentPoolListDTO> equipmentPoolList(EquipmentPoolListBO equipmentPoolListBO) {
        Page<EquipmentPoolListDTO> page = new Page<>(equipmentPoolListBO.getCurrentPage(), equipmentPoolListBO.getPerPage());
        //设备池列表
        IPage<EquipmentPoolListDTO> poolPage = baseMapper.equipmentPoolList(page, equipmentPoolListBO);
        List<EquipmentPoolListDTO> records = poolPage.getRecords();
        //组装监测因子内容
        List<SysSensorFactorConfig> sensorFactorConfig = baseService.findSensorFactorConfig();
        //监测因子内容描述map
        Map<Integer, String> mapDesc = baseService.sensorFactorDescMap();
        // 获取字典表
        List<SysDictionaryConfig> sysDictionaryConfigs = sysDictionaryConfigMapper.selectByMap(ImmutableMap.of());
        //设备种类
        final List<SysDictionaryConfig> equipmentCatagory = sysDictionaryConfigs.stream().filter(it -> it.getType() == 6).collect(Collectors.toList());
        records.forEach(it -> {
            //产品可用监测因子
            String sensorFactors = it.getSensorFactors();
            if (StrUtil.isNotBlank(sensorFactors)) {
                List<String> factorIds = Arrays.asList(sensorFactors.split(","));
                sensorFactors = sysSensorFactorConfigMapper.orderSensorFactors(factorIds);
                //组装监测因子的内容和详细监测因子
                String config = baseService.spellSensorFactorConfig(sensorFactorConfig, sensorFactors);
                it.setSensorFactors(baseService.getFactor(mapDesc, config));
                it.setSensorFactorDetails(baseService.getFactor(mapDesc, sensorFactors));
            }
            //设置设备种类
            equipmentCatagory.forEach(catagory -> {
                if (catagory.getCode().equals(it.getEquipmentCatagoryDetails())) {
                    it.setEquipmentCatagoryDetails(catagory.getName());
                }
            });
        });
        return poolPage.setRecords(records);
    }

    public String orderString(List<String> list, String sensorFactors) {
        List list1 = CommonUtil.shellSortASC(list);
        sensorFactors = "";
        for (int i = 0; i < list1.size(); i++) {
            if (i == 0) {
                sensorFactors = sensorFactors.concat(String.valueOf(list1.get(i)));
            } else {
                sensorFactors = sensorFactors.concat(",").concat(String.valueOf(list1.get(i)));
            }
        }
        return sensorFactors;
    }

    /**
     * 分页接口
     *
     * @param equipmentPoolListBO
     * @param records
     * @return
     */
    public IPage<EquipmentPoolListDTO> page(EquipmentPoolListBO equipmentPoolListBO, List<EquipmentPoolListDTO> records) {
        int start = equipmentPoolListBO.getCurrentPage() * equipmentPoolListBO.getPerPage();
        int end = start + equipmentPoolListBO.getPerPage();
        if (end > records.size()) {
            end = records.size();
        }
        Page<EquipmentPoolListDTO> page = new Page<>(equipmentPoolListBO.getCurrentPage(), equipmentPoolListBO.getPerPage());
        List list = new ArrayList();
        for (int i = start; i < end; i++) {
            list.add(records.get(i));
        }
        page.setRecords(list);
        page.setTotal(records.size());
        return page;
    }

    /**
     * 设备解除绑定
     */
    @Override
    @Transactional
    public int unbind(OptStationEquipment sysStationEquipment, String userId) {
        //查询站点所有设备信息
        QueryWrapper<SysStationEquipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_id", sysStationEquipment.getStationId())
                .in("mount_status", 1, 2);
        List<SysStationEquipment> stationEquipments = sysStationEquipmentMapper.selectList(queryWrapper);
        List<SysStationEquipment> mainEquipment = stationEquipments.stream().filter(f -> f.getMountStatus() == 1).collect(Collectors.toList());
        if (stationEquipments.size() > 1) {
            //判断解绑的设备是否为主设备,不让解绑主设备
            if (mainEquipment.size() > 0 && mainEquipment.get(0).getEquipmentId().equals(sysStationEquipment.getEquipmentId())) {
                return -1;
            }
        }
        sysStationEquipment.setOperateBy(userId);
        sysStationEquipment.setOperateTime(com.qingcloud.adminbackend.utils.DateUtil.getCurrentDateTime());
        //解除绑定
        sysStationEquipmentMapper.unbind(sysStationEquipment);
        //更改监测点状态
        sysStationMapper.updateStatus(Arrays.asList(sysStationEquipment.getStationId()), sysStationEquipment.getStationStatus());

        //解绑时前端传的mountStatus状态为原有设备绑定状态。
        //如果是主设备，清空站点和订单的绑定关系。
        QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
        query.eq("station_id", sysStationEquipment.getStationId());
        if (sysStationEquipment.getMountStatus() == 1) {
            //修改订单设备表
            SysOrderEquipment soe = new SysOrderEquipment();
            soe.setEquipmentId("");
            soe.setModifyBy(userId);
            soe.setModifyDt(new Date());
            sysOrderEquipmentMapper.update(soe, query);
            //删除多余的设备数据
            SysOrderEquipment sysOrderEquipment = sysOrderEquipmentMapper.selectOne(query);
            if (sysOrderEquipment != null) {
                //插入一条订单检测点数据
                SysOrderEquipment ins = new SysOrderEquipment();
                ins.setCreateBy(userId);
                ins.setCreateDt(new Date());
                ins.setModifyDt(new Date());
                ins.setModifyBy(userId);
                ins.setOrderId(sysOrderEquipment.getOrderId());
                ins.setEquipmentId(sysStationEquipment.getEquipmentId());
                sysOrderEquipmentMapper.insert(ins);
            }
            //如果是次设备解绑,只需要还原订单和设备的关系
        } else if (sysStationEquipment.getMountStatus() == 2) {
            SysOrderEquipment sysOrderEquipment = sysOrderEquipmentMapper.selectOne(query);
            SysOrderEquipment ins = new SysOrderEquipment();
            ins.setCreateBy(userId);
            ins.setCreateDt(new Date());
            ins.setModifyDt(new Date());
            ins.setModifyBy(userId);
            ins.setOrderId(sysOrderEquipment.getOrderId());
            ins.setEquipmentId(sysStationEquipment.getEquipmentId());
            sysOrderEquipmentMapper.insert(ins);
        }

        //修改设备组数据，首先找到所有此设备下所有设备组
        QueryWrapper<SysStationGroupEquipment> stationGroupQueryByStation = new QueryWrapper();
        stationGroupQueryByStation.eq("station_id", sysStationEquipment.getStationId());
        List<SysStationGroupEquipment> sysStationGroupEquipmentList = sysStationGroupEquipmentMapper.selectList(stationGroupQueryByStation);
        if (sysStationEquipment.getMountStatus() == 1) {
            //同一个设备可以在多个设备组种
            if (CollUtil.isNotEmpty(sysStationGroupEquipmentList)) {
                sysStationGroupEquipmentList.forEach(group -> {
                    //每个设备组的数据重新创建只有设备编号的数据
                    SysStationGroupEquipment sins = new SysStationGroupEquipment();
                    sins.setCreateBy(userId);
                    sins.setCreateDt(new Date());
                    sins.setModifyDt(new Date());
                    sins.setModifyBy(userId);
                    sins.setGroupId(group.getGroupId());
                    sins.setEquipmentId(sysStationEquipment.getEquipmentId());
                    sysStationGroupEquipmentMapper.insert(sins);
                });
                //修改设备组数据，删除设备ID，只保留监测点编号
                SysStationGroupEquipment sge = new SysStationGroupEquipment();
                sge.setModifyBy(userId);
                sge.setEquipmentId("");
                sge.setModifyDt(new Date());
                sysStationGroupEquipmentMapper.update(sge, new UpdateWrapper<SysStationGroupEquipment>().lambda()
                        .eq(SysStationGroupEquipment::getStationId, sysStationEquipment.getStationId()));
            }
            //如果是次设备解绑,只需要还原设备和设备组的关系
        } else if (sysStationEquipment.getMountStatus() == 2) {
            if (CollUtil.isNotEmpty(sysStationGroupEquipmentList)) {
                sysStationGroupEquipmentList.forEach(group -> {
                    //每个设备组的数据重新创建只有设备编号的数据
                    SysStationGroupEquipment sins = new SysStationGroupEquipment();
                    sins.setCreateBy(userId);
                    sins.setCreateDt(new Date());
                    sins.setModifyDt(new Date());
                    sins.setModifyBy(userId);
                    sins.setGroupId(group.getGroupId());
                    sins.setEquipmentId(sysStationEquipment.getEquipmentId());
                    sysStationGroupEquipmentMapper.insert(sins);
                });
            }
        }
        return 1;
    }

    /**
     * 设备绑定
     */
    @Override
    @Transactional
    public Integer bind(OptStationEquipment sysStationEquipment, String userId) {
        String productRotot = RobotServiceImpl.robotProduct;
        //判断该设备是否被绑定
        if (isBind(sysStationEquipment.getEquipmentId())) {
            return -1;
        }
        if (isDelete(sysStationEquipment.getEquipmentId())) {
            return -2;
        }
        sysStationEquipment.setOperateBy(userId);
        sysStationEquipment.setOperateTime(com.qingcloud.adminbackend.utils.DateUtil.getCurrentDateTime());
        //绑定的时候如果站点还没有主设备，就限制绑定必须为主设备
        QueryWrapper<SysStationEquipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_id", sysStationEquipment.getStationId())
                .eq("mount_status", 1);
        SysStationEquipment stationEquipment = sysStationEquipmentMapper.selectOne(queryWrapper);
        //判断 是否绑定主设备
        if (sysStationEquipment.getMountStatus() != 1 && null == stationEquipment) {
            return -5;
        } else if (sysStationEquipment.getMountStatus() == 1) {
            if (null != stationEquipment) {
                return -4;
            }
            sysStationEquipment.setIsLast(1);
        } else {
            sysStationEquipment.setIsLast(0);
        }
        //设备产品信息
        List<EquipmentProduct> equipmentProducts = sysEquipmentMapper.projectInfoByStationId(sysStationEquipment.getStationId());
        //过滤出机器人设备绑定操作
        EquipmentProduct equipmentProduct = sysEquipmentMapper.projectInfoByEquipmentId(sysStationEquipment.getEquipmentId());

        List<EquipmentProduct> productType = equipmentProducts.stream().filter(f -> f.getProductType().equals(equipmentProduct.getProductType())).collect(Collectors.toList());
        //新绑定的设备类型 如果已绑定过
        if (productType.size() > 0) {
            return -3;
        }

        //如果是机器人设备绑定站点，给机器人信息添加船舶id
        if (equipmentProduct.getProductType().equals(productRotot)) {
            saveRobotInfo(sysStationEquipment.getStationId(), sysStationEquipment.getEquipmentId());
        }
        //绑定
        sysStationEquipmentMapper.bind(sysStationEquipment);
        //更改监测点状态
        sysStationMapper.updateStatus(Arrays.asList(sysStationEquipment.getStationId()), sysStationEquipment.getStationStatus());

        //修改订单设备表
        //是主设备时 站点和订单和设备才做绑定，其余只删除多余设备和订单信息
        if (sysStationEquipment.getMountStatus() == 1) {
            SysOrderEquipment soe = new SysOrderEquipment();
            soe.setEquipmentId(sysStationEquipment.getEquipmentId());
            soe.setModifyBy(userId);
            soe.setModifyDt(new Date());
            QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
            query.eq("station_id", sysStationEquipment.getStationId());
            sysOrderEquipmentMapper.update(soe, query);
        }
        //删除多余的设备数据
        sysOrderEquipmentMapper.deleteByBind(sysStationEquipment.getEquipmentId());
        //是主设备时，站点和设备组和设备才做绑定，其余只删除多余的设备和设备组信息
        if (sysStationEquipment.getMountStatus() == 1) {
            //修改设备组与设备关系表中的状态
            SysStationGroupEquipment sge = new SysStationGroupEquipment();
            sge.setModifyBy(userId);
            sge.setEquipmentId(sysStationEquipment.getEquipmentId());
            sge.setModifyDt(new Date());
            QueryWrapper<SysStationGroupEquipment> sgeQuery = new QueryWrapper();
            sgeQuery.eq("station_id", sysStationEquipment.getStationId());
            sysStationGroupEquipmentMapper.update(sge, sgeQuery);
        }
        //删除多余的数据
        sysStationGroupEquipmentMapper.deleteByBind(sysStationEquipment.getEquipmentId());
        return 1;
    }


    private void saveRobotInfo(String stationId, String equipmentId) {
        QueryWrapper<SysStation> stationQueryWrapper = new QueryWrapper<>();
        stationQueryWrapper.eq("station_id", stationId);
        SysStation sysStation = sysStationMapper.selectOne(stationQueryWrapper);
        RobotInfo robotInfo = new RobotInfo();
        robotInfo.setSerialNumber(equipmentId);
        robotInfo.setMo(sysStation.getMoId());
        robotService.saveRobotInfo(robotInfo);
    }

    private boolean isDelete(String equipmentId) {
        if (StrUtil.isBlank(equipmentId)) {
            return true;
        }
        List<SysEquipment> sysEquipments = sysEquipmentMapper.selectByMap(ImmutableMap.of("equipment_id", equipmentId, "delete_flag", 0));
        if (CollUtil.isEmpty(sysEquipments)) {
            return true;
        }
        return false;
    }

    private Boolean isBind(String equipmentId) {
        if (StrUtil.isBlank(equipmentId)) {
            return false;
        }
        List<SysStationEquipment> sysStationEquipments = sysStationEquipmentMapper.selectByMap(ImmutableMap.of("equipment_id", equipmentId, "mount_status", 1));
        if (!CollUtil.isEmpty(sysStationEquipments)) {
            return true;
        }
        return false;
    }

    /**
     * 更换绑定
     *
     * @param sysStationEquipment
     * @param userId
     */
    @Override
    @Transactional
    public Integer changeBind(OptStationEquipment sysStationEquipment, String userId) {
        if (isBind(sysStationEquipment.getEquipmentId())) {
            return -1;
        }
        if (isDelete(sysStationEquipment.getEquipmentId())) {
            return -2;
        }
        //加入以前绑定的设备数据
        QueryWrapper<SysOrderEquipment> tempQ = new QueryWrapper<>();
        tempQ.eq("station_id", sysStationEquipment.getStationId());
        SysOrderEquipment sysOrderEquipment = sysOrderEquipmentMapper.selectOne(tempQ);

        //修改设备组数据
        QueryWrapper<SysStationGroupEquipment> sgeQueryte = new QueryWrapper();
        sgeQueryte.eq("station_id", sysStationEquipment.getStationId());
        SysStationGroupEquipment sysStationGroupEquipment = sysStationGroupEquipmentMapper.selectOne(sgeQueryte);

        sysStationEquipment.setOperateBy(userId);
        sysStationEquipment.setOperateTime(com.qingcloud.adminbackend.utils.DateUtil.getCurrentDateTime());
        //解绑现在绑定的设备
        sysStationEquipmentMapper.unbind(sysStationEquipment);
        //绑定
        sysStationEquipmentMapper.bind(sysStationEquipment);
        //修改last
        sysStationEquipmentMapper.updateIsLast(sysStationEquipment.getId(), sysStationEquipment.getStationId());
        //修改订单设备表
        SysOrderEquipment soe = new SysOrderEquipment();
        soe.setEquipmentId(sysStationEquipment.getEquipmentId());
        soe.setModifyBy(userId);
        soe.setModifyDt(new Date());
        QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
        query.eq("station_id", sysStationEquipment.getStationId());
        sysOrderEquipmentMapper.update(soe, query);
        //删除多余的设备数据
        sysOrderEquipmentMapper.deleteByBind(sysStationEquipment.getEquipmentId());
        if (sysOrderEquipment != null) {
            SysOrderEquipment ins = new SysOrderEquipment();
            ins.setCreateBy(userId);
            ins.setCreateDt(new Date());
            ins.setModifyDt(new Date());
            ins.setModifyBy(userId);
            ins.setOrderId(sysOrderEquipment.getOrderId());
            ins.setEquipmentId(sysOrderEquipment.getEquipmentId());
            sysOrderEquipmentMapper.insert(ins);
        }

        //修改设备组与设备关系表中的状态
        SysStationGroupEquipment sge = new SysStationGroupEquipment();
        sge.setModifyBy(userId);
        sge.setEquipmentId(sysStationEquipment.getEquipmentId());
        sge.setModifyDt(new Date());
        QueryWrapper<SysStationGroupEquipment> sgeQuery = new QueryWrapper();
        sgeQuery.eq("station_id", sysStationEquipment.getStationId());
        sysStationGroupEquipmentMapper.update(sge, sgeQuery);
        //删除多余的数据
        sysStationGroupEquipmentMapper.deleteByBind(sysStationEquipment.getEquipmentId());
        if (sysStationGroupEquipment != null) {
            //插入一条
            SysStationGroupEquipment sins = new SysStationGroupEquipment();
            sins.setCreateBy(userId);
            sins.setCreateDt(new Date());
            sins.setModifyDt(new Date());
            sins.setModifyBy(userId);
            sins.setGroupId(sysStationGroupEquipment.getGroupId());
            sins.setEquipmentId(sysStationGroupEquipment.getEquipmentId());
            sysStationGroupEquipmentMapper.insert(sins);
        }
        return 1;
    }

    /**
     * 更换站点主设备绑定
     *
     * @param sysStationEquipment
     * @param userId
     */
    @Override
    @Transactional
    public Integer replaceBind(OptStationEquipment sysStationEquipment, String userId) {
        sysStationEquipment.setOperateBy(userId);
        if (isDelete(sysStationEquipment.getEquipmentId())) {
            return -2;
        }
        QueryWrapper<SysStationEquipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_id", sysStationEquipment.getStationId());
        List<SysStationEquipment> sysStationEquipmentList = sysStationEquipmentMapper.selectList(queryWrapper);
        List<SysStationEquipment> hostEquipments = sysStationEquipmentList.stream().filter(f -> f.getMountStatus() == 1).collect(Collectors.toList());
        //站点没有主设备的情况下 直接修改设备为主设备
        if (hostEquipments.size() == 0) {
            SysStationEquipment upStationEquipment = new SysStationEquipment();
            upStationEquipment.setMountStatus(1);
            upStationEquipment.setIsLast(1);
            upStationEquipment.setUnbindTime(LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER));
            upStationEquipment.setOperateBy(userId);
            QueryWrapper<SysStationEquipment> upWrapper = new QueryWrapper();
            upWrapper.eq("equipment_id", sysStationEquipment.getEquipmentId())
                    .eq("station_id", sysStationEquipment.getStationId());
            int up = sysStationEquipmentMapper.update(upStationEquipment, upWrapper);
            QueryWrapper<SysStationEquipment> newWrapperNew = new QueryWrapper();
            newWrapperNew.eq("equipment_id", sysStationEquipment.getEquipmentId())
                    .eq("station_id", sysStationEquipment.getStationId())
                    .eq("mount_status", 1);
            SysStationEquipment newSysStationEquipment = sysStationEquipmentMapper.selectOne(newWrapperNew);
            sysStationEquipmentMapper.updateIsLast(newSysStationEquipment.getId(), sysStationEquipment.getStationId());
            if (up == 1) {
                //将主设备和订单和设备绑定
                if (upStationEquipment.getMountStatus() == 1) {
                    SysOrderEquipment soe = new SysOrderEquipment();
                    soe.setEquipmentId(sysStationEquipment.getEquipmentId());
                    soe.setModifyBy(userId);
                    soe.setModifyDt(new Date());
                    QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
                    query.eq("station_id", sysStationEquipment.getStationId());
                    sysOrderEquipmentMapper.update(soe, query);
                    //修改设备组与设备关系表中的状态
                    SysStationGroupEquipment sge = new SysStationGroupEquipment();
                    sge.setModifyBy(userId);
                    sge.setEquipmentId(sysStationEquipment.getEquipmentId());
                    sge.setModifyDt(new Date());
                    QueryWrapper<SysStationGroupEquipment> sgeQuery = new QueryWrapper();
                    sgeQuery.eq("station_id", sysStationEquipment.getStationId());
                    sysStationGroupEquipmentMapper.update(sge, sgeQuery);
                }
                return 1;
            } else {
                return -3;
            }
        }
        //如果有主设备的情况 将原有的设备设置为次设备
        if (hostEquipments.size() > 0) {
            SysStationEquipment upStationEquipment = new SysStationEquipment();
            upStationEquipment.setMountStatus(2);
            upStationEquipment.setOperateBy(userId);
            upStationEquipment.setUnbindTime(LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER));
            upStationEquipment.setOperateBy(userId);
            QueryWrapper<SysStationEquipment> upWrapper = new QueryWrapper();
            upWrapper.eq("equipment_id", hostEquipments.get(0).getEquipmentId())
                    .eq("station_id", hostEquipments.get(0).getStationId())
                    .eq("mount_status", 1);
            int up = sysStationEquipmentMapper.update(upStationEquipment, upWrapper);
            if (up != 1) {
                return -4;
            }
            //设置新的主设备状态
            SysStationEquipment upStationEquipmentNew = new SysStationEquipment();
            upStationEquipmentNew.setMountStatus(1);
            upStationEquipmentNew.setOperateBy(userId);
            upStationEquipmentNew.setIsLast(1);
            upStationEquipmentNew.setUnbindTime(LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER));
            upStationEquipmentNew.setOperateBy(userId);
            QueryWrapper<SysStationEquipment> upWrapperNew = new QueryWrapper();
            upWrapperNew.eq("equipment_id", sysStationEquipment.getEquipmentId())
                    .eq("station_id", sysStationEquipment.getStationId())
                    .eq("mount_status", 2);
            int up2 = sysStationEquipmentMapper.update(upStationEquipmentNew, upWrapperNew);

            QueryWrapper<SysStationEquipment> newWrapperNew = new QueryWrapper();
            newWrapperNew.eq("equipment_id", sysStationEquipment.getEquipmentId())
                    .eq("station_id", sysStationEquipment.getStationId())
                    .eq("mount_status", 1);
            SysStationEquipment newSysStationEquipment = sysStationEquipmentMapper.selectOne(newWrapperNew);
            sysStationEquipmentMapper.updateIsLast(newSysStationEquipment.getId(), sysStationEquipment.getStationId());
            //将主设备和订单和设备绑定
            if (upStationEquipmentNew.getMountStatus() == 1) {
                SysOrderEquipment soe = new SysOrderEquipment();
                soe.setEquipmentId(sysStationEquipment.getEquipmentId());
                soe.setModifyBy(userId);
                soe.setModifyDt(new Date());
                QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
                query.eq("station_id", sysStationEquipment.getStationId());
                sysOrderEquipmentMapper.update(soe, query);
                //修改设备组与设备关系表中的状态
                SysStationGroupEquipment sge = new SysStationGroupEquipment();
                sge.setModifyBy(userId);
                sge.setEquipmentId(sysStationEquipment.getEquipmentId());
                sge.setModifyDt(new Date());
                QueryWrapper<SysStationGroupEquipment> sgeQuery = new QueryWrapper();
                sgeQuery.eq("station_id", sysStationEquipment.getStationId());
                sysStationGroupEquipmentMapper.update(sge, sgeQuery);
            }
            if (up2 != 1) {
                return -3;
            }
        }
        //更改监测点状态
        sysStationMapper.updateStatus(Arrays.asList(sysStationEquipment.getStationId()), sysStationEquipment.getStationStatus());
        return 1;
    }

    @Override
    public List<SysDictionaryConfig> findEnableWorkMode(String equipmentId) {
        //获取设备可用工作模式
        String enableWorkMode = sysEquipmentMapper.findEnableWorkMode(equipmentId);
        if (StringUtils.isEmpty(enableWorkMode)) {
            return null;
        }
        List<String> enableWorkModeList = Arrays.asList(enableWorkMode.split(","));
        // 获取工作模式类型
        List<SysDictionaryConfig> sysDictionaryConfigList = sysDictionaryConfigMapper.findByType(5);

        return sysDictionaryConfigList.stream().filter(
                it -> enableWorkModeList.contains(it.getCode())
        ).collect(Collectors.toList());
    }


    @Override
    public IPage<EquipmentListDTO> listEquipment(EquipmentListPara equipmentListPara, String userId, boolean isAdmin, boolean isFullAdmin) {

        Page<EquipmentListDTO> page = new Page<>(equipmentListPara.getCurrentPage(), equipmentListPara.getPerPage());

        IPage<EquipmentListDTO> resultList = null;

        /*
        //是否为超级管理员或完全管理权限用户
        if (isAdmin || isFullAdmin) {
            resultList = sysEquipmentMapper.equipmentMgrList(page, equipmentListPara);
            equipmentListBudingData(resultList);
        } else {

            resultList = sysEquipmentMapper.equipmentList(page, equipmentListPara, userId);
            equipmentListBudingData(resultList);
        }
         */

        List<ModelDTO> equipments = baseService.getEquipmentIds(userId, equipmentListPara.getOrderIds(), equipmentListPara.getOrgIds(), equipmentListPara.getPoolFlag());
        // 获取EquipmentIds
        List<String> equipmentIds = new ArrayList<>();
        equipments.forEach(equipment -> {
            equipmentIds.add(equipment.getModelId());
        });
        equipmentListPara.setEquipmentIds(equipmentIds);

        // 如果有设备Id执行
        if (equipmentIds.size() > 0) {
            // 获取设备列表
            resultList = sysEquipmentMapper.equipmentList(page, equipmentListPara, userId);
            equipmentListBudingData(resultList);

            // 组装读写权限和设备池标识
            List<EquipmentListDTO> equipmentList = resultList.getRecords();
            equipments.forEach(modelDTO -> {
                equipmentList.forEach(equipmentListDTO -> {
                    if (modelDTO.getModelId().equals(equipmentListDTO.getEquipmentId())) {
                        equipmentListDTO.setReadAuth(String.valueOf(modelDTO.getReadAuth()));
                        equipmentListDTO.setManageAuth(String.valueOf(modelDTO.getManageAuth()));
                        equipmentListDTO.setIsEquipmentPool(String.valueOf(modelDTO.getIspool()));
                    }
                });
            });
        } else {
            resultList = null;
        }

        return resultList;
    }

    /**
     * 数据导出
     *
     * @param equipmentListPara
     * @param userId
     * @param isAdmin
     * @param isFullAdmin
     * @return
     */
    @Override
    public List<EquipmentExportDTO> exportData(EquipmentListPara equipmentListPara, String userId, boolean isAdmin, boolean isFullAdmin) {
        List<ModelDTO> equipments = baseService.getEquipmentIds(userId, equipmentListPara.getOrderIds(), equipmentListPara.getOrgIds(), equipmentListPara.getPoolFlag());
        // 获取EquipmentIds
        List<String> equipmentIds = new ArrayList<>();
        equipments.forEach(equipment -> {
            equipmentIds.add(equipment.getModelId());
        });
        equipmentListPara.setEquipmentIds(equipmentIds);

        List<EquipmentExportDTO> resultList;

        // 如果有设备Id执行
        if (equipmentIds.size() > 0) {
            // 获取设备列表
            resultList = sysEquipmentMapper.exportData(equipmentListPara, userId);
            equipmentListBudingExportData(resultList);
        } else {
            resultList = null;
        }

        return resultList;
    }

    public void equipmentListBudingExportData(List<EquipmentExportDTO> resultList) {
        List<SysStationMoDTO> stationMos = sysStationGroupMapper.findStationMo();
        // 获取四参,六参等
        List<SysSensorFactorConfig> configList = baseService.findSensorFactorConfig();
        //监测因子内容描述map
        Map<Integer, String> mapDesc = baseService.sensorFactorDescMap();
        //监测因子处理
        resultList.forEach(it -> {
            // 如果传感器的监测因子为空取可用监测因子
            String sensor = it.getSensorFactors();
            if (StringUtils.isEmpty(sensor)) {
                it.setSensorFactors(it.getUseSensorFactors());
            }
            buildingSensorExport(it, configList, mapDesc);
            // 监测点的状态需要变为已解绑。监测点列不需要展示解绑的监测点
            if (!StringUtils.isEmpty(it.getMountStatus()) && it.getMountStatus().equals("0")) {
                it.setStationName("");
            }
        });
    }

    private void buildingSensorExport(EquipmentExportDTO equipmentListDTO, List<SysSensorFactorConfig> configList, Map<Integer, String> mapDesc) {
        // 监测因子转化字符串
        String tmpSensorFactor = equipmentListDTO.getSensorFactors();
        if (StrUtil.isNotBlank(tmpSensorFactor)) {
            List<String> factorIds = Arrays.asList(tmpSensorFactor.split(","));
            // 排序
            tmpSensorFactor = sysSensorFactorConfigMapper.orderSensorFactors(factorIds);
            //组装监测因子的内容和详细监测因子
            String config = baseService.spellSensorFactorConfig(configList, tmpSensorFactor);
            // 转化字符串
            String sensorFactor = baseService.getFactor(mapDesc, config);
            equipmentListDTO.setSensorFactors(sensorFactor);
            // 监测因子tips
            String factorsTips = baseService.getFactor(mapDesc, tmpSensorFactor);
            equipmentListDTO.setSensorFactorsTips(factorsTips);
        }
    }


    /**
     * 功能描述: 设备管理列表组装数组
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2019/4/23 18:10
     */
    public void equipmentListBudingData(IPage<EquipmentListDTO> resultList) {
        List<EquipmentListDTO> equipmentList = resultList.getRecords();
        List<SysStationMoDTO> stationMos = sysStationGroupMapper.findStationMo();
        // 获取四参,六参等
        List<SysSensorFactorConfig> configList = baseService.findSensorFactorConfig();
        //监测因子内容描述map
        Map<Integer, String> mapDesc = baseService.sensorFactorDescMap();
        //监测因子处理
        equipmentList.forEach(it -> {

            // 组装空间
            if (!StringUtils.isEmpty(it.getMoId())) {
                splitString(it, stationMos);
            }

            // 组装设备传感器状态
            if (!StringUtils.isEmpty(it.getSensorStatus())) {
                String status = it.getSensorStatus();
                if (status.contains("2") || status.contains("3") || status.contains("4")) {
                    it.setSensorStatus("0");
                } else if (status.contains("6")) {
                    it.setSensorStatus(status);
                } else {
                    it.setSensorStatus("1");
                }
            }
            // 如果传感器的监测因子为空取可用监测因子
            String sensor = it.getSensorFactors();
            if (StringUtils.isEmpty(sensor)) {
                it.setSensorFactors(it.getUseSensorFactors());
            }
            buildingSensor(it, configList, mapDesc);

            // 监测点的状态需要变为已解绑。监测点列不需要展示解绑的监测点
            if (!StringUtils.isEmpty(it.getMountStatus()) && it.getMountStatus().equals("0")) {
                it.setStationName("");
            }
        });
    }

    /**
     * 功能描述: 组装监测因子
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2019/4/26 17:09
     */
    private void buildingSensor(EquipmentListDTO equipmentListDTO, List<SysSensorFactorConfig> configList, Map<Integer, String> mapDesc) {
        // 监测因子转化字符串
        String tmpSensorFactor = equipmentListDTO.getSensorFactors();
        if (StrUtil.isNotBlank(tmpSensorFactor)) {
            List<String> factorIds = Arrays.asList(tmpSensorFactor.split(","));
            // 排序
            tmpSensorFactor = sysSensorFactorConfigMapper.orderSensorFactors(factorIds);
            //组装监测因子的内容和详细监测因子
            String config = baseService.spellSensorFactorConfig(configList, tmpSensorFactor);
            // 转化字符串
            String sensorFactor = baseService.getFactor(mapDesc, config);
            equipmentListDTO.setSensorFactors(sensorFactor);
            // 监测因子tips
            String factorsTips = baseService.getFactor(mapDesc, tmpSensorFactor);
            equipmentListDTO.setSensorFactorsTips(factorsTips);
        }
    }

    /**
     * 功能描述: 组装空间名称
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2019/4/23 16:51
     */
    private void splitString(EquipmentListDTO equipmentListDTO, List<SysStationMoDTO> stationMos) {
        List<String> list1 = new ArrayList<>();
        int z = 5;
        int num = (equipmentListDTO.getMoId().length() / 5) - 1;
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                list1.add(equipmentListDTO.getMoId().substring(0, equipmentListDTO.getMoId().length() - z));
                z = z + 5;
            }
        }
        list1.add(equipmentListDTO.getMoId());
        String capation = "";
        for (SysStationMoDTO it : stationMos) {
            if (list1.contains(it.getId())) {
                capation += it.getCapation();
            }
        }
        equipmentListDTO.setSpace(capation);
        equipmentListDTO.setCapation(equipmentListDTO.getProDesc() + capation);
    }

    private List<String> getOrderList(List<String> orgids) {

        return null;
    }

    /**
     * 添加或者修改设备
     *
     * @param addEquipmentDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer optEquipment(AddEquipmentDTO addEquipmentDTO, String userId) {
        //添加设备基础信息
        SysEquipment equipment = new SysEquipment();
        equipment.setEquipmentId(addEquipmentDTO.getEquipmentId());
        equipment.setProductType(addEquipmentDTO.getProductType());
        equipment.setManufacturer(addEquipmentDTO.getManufacturer());
        equipment.setFactoryTime(addEquipmentDTO.getFactoryTime());
        equipment.setPhoneNum(addEquipmentDTO.getPhoneNum());
        equipment.setUploadInternel(1);
        equipment.setCollectInternel(1);
        equipment.setOnlineControl(addEquipmentDTO.getOnlineControl());
        equipment.setProductKey(WamingConstant.MQTT_PROTOCOL_PRODUCT_KEY);
        equipment.setIspreheat(addEquipmentDTO.getIspreheat());
        List<SensorParam> sensors = addEquipmentDTO.getSensors();
        //监测改订单是否被删除
        String orderId = addEquipmentDTO.getOrderId();
        if (StrUtil.isNotBlank(orderId)) {
            QueryWrapper<SysOrder> orderQuery = new QueryWrapper();
            orderQuery.eq("id", orderId);
            orderQuery.eq("delete_flag", 0);
            Long count = sysOrderMapper.selectCount(orderQuery);
            if (count <= 0) {
                return -6;
            }
        }
        //监测监测因子是否重复
        if (checkSensorFactors(sensors)) {
            return -4;
        }
        String robotProduct = RobotServiceImpl.robotProduct;
        if (addEquipmentDTO.getId() == null) {
            //判断
            List<SysEquipment> sysEquipments = baseMapper.selectByMap(ImmutableMap.of("equipment_id", addEquipmentDTO.getEquipmentId(), "delete_flag", 0));
            if (CollUtil.isNotEmpty(sysEquipments)) {
                return -5;
            }
            int insert = addEquipment(addEquipmentDTO, userId, equipment, sensors);
            if (insert > 0) {
                //如果是机器人设备，将信息同步到机器人表
                if (addEquipmentDTO.getProductType().equals(robotProduct)) {
                    RobotInfo info = new RobotInfo();
                    info.setSerialNumber(addEquipmentDTO.getEquipmentId());
                    info.setEnable(1);
                    int ro = robotService.saveRobotInfo(info);
                    if (ro != 1) {
                        throw new WmCommonException("未检测到机器人，基础信息同步失败！");
                    }
                }
            }
            return insert > 0 ? 2 : -2;
        } else {
            int update = updateEquipment(addEquipmentDTO, userId, equipment, sensors);
            if (update > 0) {
                //修改时设备产品类型变动 机器人产品类型
                QueryWrapper<SysEquipment> wrapper = new QueryWrapper<>();
                wrapper.eq("equipment_id", addEquipmentDTO.getEquipmentId());
                SysEquipment sysEquipment = sysEquipmentMapper.selectOne(wrapper);
                if (!sysEquipment.getProductType().equals(robotProduct) &&
                        addEquipmentDTO.getProductType().equals(robotProduct)) {
                    RobotInfo info = new RobotInfo();
                    info.setSerialNumber(addEquipmentDTO.getEquipmentId());
                    info.setEnable(1);
                    int robot = robotService.saveRobotInfo(info);
                    if (robot != 1) {
                        throw new WmCommonException("未检测到机器人，基础信息同步失败！");
                    }
                }
            }
            return update > 0 ? 3 : -3;
        }

    }

    /**
     * 校验所有的传感器所选的监测因子是否重复
     *
     * @param sensors
     * @return
     */
    private Boolean checkSensorFactors(List<SensorParam> sensors) {
        if (CollUtil.isEmpty(sensors)) {
            return false;
        }
        List<Integer> allFactorIds = new ArrayList<>();
        sensors.stream().forEach(sensor -> {
            List<Integer> factorIds = sensor.getFactorId();
            allFactorIds.addAll(factorIds);
        });
        return allFactorIds.size() != new HashSet<>(allFactorIds).size();
    }

    private Integer updateEquipment(AddEquipmentDTO addEquipmentDTO, String userId, SysEquipment equipment, List<SensorParam> sensors) {
        //修改
        equipment.setId(addEquipmentDTO.getId());
        equipment.setStatus(addEquipmentDTO.getStatus());
        equipment.setEquipmentCatagory(addEquipmentDTO.getEquipmentCatagory());
        int update = sysEquipmentMapper.updateById(equipment);
        //修改订单
        if (update > 0) {
            String orderId = addEquipmentDTO.getOrderId();
            if (StrUtil.isNotBlank(orderId)) {
                //当前设备是订单中的设备
                //查询订单中绑定的监测点
                QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
                query.eq("equipment_id", addEquipmentDTO.getEquipmentId());
                SysOrderEquipment orderEquipment = sysOrderEquipmentMapper.selectOne(query);
                String stationId = orderEquipment.getStationId();
                if (!orderId.equals(orderEquipment.getOrderId())) {
                    //新订单编号与老订单编号不一致时，需要解绑监测点，删除旧设备订单关联数据
                    if (StrUtil.isBlank(stationId)) {
                        //设备没有监测点的绑定
                        //删除旧的订单
                        sysOrderEquipmentMapper.deleteByMap(ImmutableMap.of("equipment_id", orderEquipment.getEquipmentId()));
                    } else {
                        //监测点解绑
                        SysStationEquipment sse = new SysStationEquipment();
                        sse.setMountStatus(0);
                        sse.setUnbindTime(LocalDateTime.now().format(WamingConstant.NORMAL_FULL_FORMATTER));
                        QueryWrapper<SysStationEquipment> updateQuery = new QueryWrapper();
                        updateQuery.eq("station_id", stationId);
                        updateQuery.eq("mount_status", 1);
                        sysStationEquipmentMapper.update(sse, updateQuery);
                        //解除设备与订单绑定
                        sysOrderEquipmentMapper.updateEquipmentsByIds(orderEquipment.getOrderId(), orderEquipment.getStationId());
                    }
                    //绑定新的订单
                    SysOrderEquipment insertParam = new SysOrderEquipment();
                    insertParam.setOrderId(orderId);
                    insertParam.setEquipmentId(orderEquipment.getEquipmentId());
                    insertParam.setCreateBy(userId);
                    insertParam.setCreateDt(new Date());
                    insertParam.setModifyBy(userId);
                    insertParam.setModifyDt(new Date());
                    sysOrderEquipmentMapper.insert(insertParam);
                }
            }
            //删除所有传感器
            SysSensor updateSeneor = new SysSensor();
            updateSeneor.setEquipmentId("");
            QueryWrapper<SysSensor> sensorQuery = new QueryWrapper<>();
            sensorQuery.eq("equipment_id", addEquipmentDTO.getEquipmentId());
            sysSensorMapper.update(updateSeneor, sensorQuery);
            //修改传感器
            sensors.forEach(s -> {
                String sensorId = s.getSensorId();
                Integer count = sysSensorMapper.existSensor(sensorId);
                if (count > 1) {
                    //修改
                    SysSensor updateSensor = new SysSensor();
                    updateSensor.setFactoryTime(s.getFactoryTime());
                    updateSensor.setSupplier(s.getSupplier());
                    updateSensor.setCatagory(s.getCatagory());
                    updateSensor.setFactoryTime(s.getFactoryTime());
                    QueryWrapper<SysSensor> sensorQueryWrapper = new QueryWrapper<>();
                    sensorQueryWrapper.eq("sensor_id", s.getSensorId());
                    sysSensorMapper.update(updateSensor, sensorQueryWrapper);
                    //更新因子
                    List<Integer> factorId = s.getFactorId();
                    //删除以前对应的因子
                    SysSensorFactor updateFactor = new SysSensorFactor();
                    updateFactor.setDeleteFlag(1);
                    QueryWrapper<SysSensorFactor> queryFactor = new QueryWrapper<>();
                    queryFactor.eq("sensor_id", s.getSensorId());
                    sysSensorFactorMapper.update(updateFactor, queryFactor);
                    //添加新的因子
                    factorId.forEach(f -> {
                        QueryWrapper<SysSensorFactor> ssf = new QueryWrapper<>();
                        ssf.eq("sensor_id", s.getSensorId());
                        ssf.eq("factor_id", f);
                        ssf.eq("delete_flag", 1);
                        Long factorNum = sysSensorFactorMapper.selectCount(ssf);
                        if (factorNum > 0) {
                            //已经存在，更新为delete_flag = 0
                            SysSensorFactor updateFactor2 = new SysSensorFactor();
                            updateFactor2.setDeleteFlag(0);
                            QueryWrapper<SysSensorFactor> queryFactor2 = new QueryWrapper<>();
                            queryFactor2.eq("sensor_id", s.getSensorId());
                            queryFactor2.eq("factor_id", f);
                            queryFactor2.eq("delete_flag", 1);
                            sysSensorFactorMapper.update(updateFactor2, queryFactor2);
                        } else {
                            SysSensorFactor factor = new SysSensorFactor();
                            factor.setSensorId(s.getSensorId());
                            factor.setDeleteFlag(0);
                            factor.setFactorId(f);
                            sysSensorFactorMapper.insert(factor);
                        }
                    });
                } else {
                    //添加
                    //新增传感器并绑定
                    insertSensor(addEquipmentDTO, s);
                    List<Integer> factorIds = s.getFactorId();
                    //插入监测因子
                    insertFactor(s, factorIds);
                }
            });
        }
        return update;
    }

    private int addEquipment(AddEquipmentDTO addEquipmentDTO, String userId, SysEquipment equipment, List<SensorParam> sensors) {
        //新增
        equipment.setCreateBy(userId);
        equipment.setCreateDt(new Date());
        equipment.setModifyBy(userId);
        equipment.setModifyDt(new Date());
        equipment.setRunningMode(2);
        if (StringUtils.isEmpty(equipment.getFactoryTime())) {
            equipment.setFactoryTime(null);
        }
        int insert = sysEquipmentMapper.insert(equipment);
        if (insert > 0) {
            //添加传感器
            //穿过来的都是闲置的，或者新增的
            sensors.forEach(s -> {
                String sensorId = s.getSensorId();
                Integer count = sysSensorMapper.existSensor(sensorId);
                if (count > 0) {
                    //存在，修改绑定
                    sysSensorMapper.updateBind(sensorId, addEquipmentDTO.getEquipmentId());
                } else {
                    //新增传感器并绑定
                    insertSensor(addEquipmentDTO, s);
                    List<Integer> factorIds = s.getFactorId();
                    //插入监测因子
                    insertFactor(s, factorIds);

                }
            });
        }
        return insert;
    }

    private void insertFactor(SensorParam s, List<Integer> factorIds) {
        factorIds.forEach(factorId -> {
            SysSensorFactor sysSensorFactor = new SysSensorFactor();
            sysSensorFactor.setFactorId(factorId);
            sysSensorFactor.setSensorId(s.getSensorId());
            sysSensorFactor.setDeleteFlag(0);
            sysSensorFactorMapper.insert(sysSensorFactor);
        });
    }

    /**
     * 设备基本信息
     *
     * @param equipmentId
     * @return
     */
    @Override
    public SysEquipmentDetailsDTO equipmentDetails(String equipmentId, String userId, boolean isAdmin) {
        SysEquipmentDetailsDTO equipmentDetails = sysEquipmentMapper.equipmentDetails(equipmentId);
        if (equipmentDetails == null) {
            return null;
        }
        List<UserRoleVO> roles = sysUserRoleMapper.findRoleByUserId(userId);
        List<Integer> roleIds = new ArrayList<>();
        roles.forEach(it -> {
            roleIds.add(it.getId());
        });
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (isAdmin || sysUser.getAdminFlag() == 1) {
            equipmentDetails.setManageAuth(1);
            equipmentDetails.setReadAuth(1);
        }
        //客户设备管理
        if (equipmentDetails.getManageAuth() != 1) {
            SysEquipmentDetailsDTO readDto = sysUserOrgMgrMapper.findOrgMgrByEquipmentId(equipmentId, userId);
            if (readDto != null) {
                equipmentDetails.setManageAuth(readDto.getManageAuth());
                if (equipmentDetails.getReadAuth() != 1) {
                    equipmentDetails.setReadAuth(readDto.getReadAuth());
                }
            }
        }
        //订单设备管理
        if (equipmentDetails.getManageAuth() != 1) {
            SysEquipmentDetailsDTO readDto = sysUserOrderStationmgrMapper.findOrderMgrByEquipmentId(equipmentId, userId);
            if (readDto != null) {
                equipmentDetails.setManageAuth(readDto.getManageAuth());
                if (equipmentDetails.getReadAuth() != 1) {
                    equipmentDetails.setReadAuth(readDto.getReadAuth());
                }
            }
        }
        //组装监测因子的内容
        List<String> list = Arrays.asList(equipmentDetails.getSensorFactors().split(","));
        List<SysSensorFactorConfigDTO> factorMap = sysSensorFactorConfigMapper.findByIds(list);
        //设备监测因子
        equipmentDetails.setFactors(factorMap);
        //传感器监测因子
        List<SysSensorFactorConfigDTO> sensors = sysSensorFactorMapper.findByEquipmentId(equipmentDetails.getEquipmentId());
        equipmentDetails.setSensors(sensors);
        // 获取字典表
        List<SysDictionaryConfig> sysDictionaryConfigs = sysDictionaryConfigMapper.selectByMap(ImmutableMap.of());
        //设备状态
        final List<SysDictionaryConfig> status = sysDictionaryConfigs.stream().filter(it -> it.getType() == 4).collect(Collectors.toList());
        status.forEach(it -> {
            if (it.getCode().equals(equipmentDetails.getStatus())) {
                equipmentDetails.setStatusName(it.getName());
            }
        });
        //设备运行模式
        final List<SysDictionaryConfig> runningModes = sysDictionaryConfigs.stream().filter(it -> it.getType() == 5).collect(Collectors.toList());
        runningModes.forEach(it -> {
            if (it.getCode().equals(equipmentDetails.getRunningMode())) {
                equipmentDetails.setRunningMode(it.getName());
            }
        });
        //设备种类
        final List<SysDictionaryConfig> equipmentCatagory = sysDictionaryConfigs.stream().filter(it -> it.getType() == 6).collect(Collectors.toList());
        equipmentCatagory.forEach(it -> {
            if (it.getCode().equals(equipmentDetails.getEquipmentCatagory())) {
                equipmentDetails.setEquipmentCatagoryName(it.getName());
            }
        });
        //协议类型
        final List<SysDictionaryConfig> verifyStatuss = sysDictionaryConfigs.stream().filter(it -> it.getType() == 3).collect(Collectors.toList());
        verifyStatuss.forEach(it -> {
            if (it.getCode().equals(equipmentDetails.getProtocolCoe())) {
                equipmentDetails.setProtocolCoe(it.getName());
            }
        });
        //设备二维码
        ProductTypeEnum productTypeEnum = ProductTypeEnum.getByCode(equipmentDetails.getProductId());
        equipmentDetails.setQrcode(productTypeEnum.qrcodePrefix + AesUtil.encrypt(equipmentDetails.getEquipmentId()));
        return equipmentDetails;
    }

    private void insertSensor(AddEquipmentDTO addEquipmentDTO, SensorParam s) {
        SysSensor sensor = new SysSensor();
        sensor.setSensorId(s.getSensorId());
        sensor.setEquipmentId(addEquipmentDTO.getEquipmentId());
        sensor.setCatagory(s.getCatagory());
        sensor.setSupplier(s.getSupplier());
        sensor.setFactoryTime(s.getFactoryTime());
        sensor.setSensorLife(100);
        sensor.setOnlineTime(com.qingcloud.adminbackend.utils.DateUtil.getCurrentDateTime());
        sysSensorMapper.insert(sensor);
    }

    /**
     * 删除设备
     *
     * @param equipmentIds
     * @return
     */
    @Override
    @Transactional
    public Integer detele(List<String> equipmentIds, String userId) {
        if (CollUtil.isEmpty(equipmentIds)) {
            return -1;
        }
        for (String eId : equipmentIds) {
            //是否存在绑定
            QueryWrapper<SysStationEquipment> query = new QueryWrapper();
            query.eq("equipment_id", eId);
            query.in("mount_status", 1, 2);
            //目前一个设备只会绑定一个站点
            SysStationEquipment stationEquipment = sysStationEquipmentMapper.selectOne(query);
            if (null != stationEquipment) {
                if (stationEquipment.getMountStatus() == 1) {
                    return -2;
                }
                //解绑设备
                //解除绑定
                SysStationEquipment sse = new SysStationEquipment();
                sse.setMountStatus(0);
                sse.setOperateBy(userId);
                sse.setUnbindTime(com.qingcloud.adminbackend.utils.DateUtil.getCurrentDateTime());
                QueryWrapper<SysStationEquipment> query2 = new QueryWrapper<>();
                query2.eq("equipment_id", eId);
                query2.in("mount_status", 1, 2);
                sysStationEquipmentMapper.update(sse, query2);
            }
            //机器人基础信息
            QueryWrapper<SysEquipment> wrapper = new QueryWrapper<>();
            wrapper.eq("equipment_id", eId);
            SysEquipment sysEquipment = sysEquipmentMapper.selectOne(wrapper);
            if (null != sysEquipment && sysEquipment.getProductType().equals(RobotServiceImpl.robotProduct)) {
                robotService.delectRobot(eId);
            }
            //订单解除
            QueryWrapper<SysOrderEquipment> querySe = new QueryWrapper<>();
            querySe.eq("equipment_id", eId);
            SysOrderEquipment sysOrderEquipment = sysOrderEquipmentMapper.selectOne(querySe);
            if (sysOrderEquipment != null) {
                if (StrUtil.isBlank(sysOrderEquipment.getStationId())) {
                    //监测点是空的，则删除这个数据
                    sysOrderEquipmentMapper.delete(querySe);
                } else {
                    SysOrderEquipment soe = new SysOrderEquipment();
                    soe.setEquipmentId("");
                    soe.setModifyBy(userId);
                    soe.setModifyDt(new Date());
                    QueryWrapper<SysOrderEquipment> query3 = new QueryWrapper<>();
                    query3.eq("equipment_id", eId);
                    sysOrderEquipmentMapper.update(soe, query3);
                }
            }
            //解绑监测因子
            SysSensor sensor = new SysSensor();
            sensor.setEquipmentId("");
            sensor.setStatus(2);
            QueryWrapper<SysSensor> sensorQuery = new QueryWrapper<>();
            sensorQuery.eq("equipment_id", eId);
            sysSensorMapper.update(sensor, sensorQuery);
            SysEquipmentBackup backup = new SysEquipmentBackup();
            if (null != sysEquipment) {
                BeanUtil.copyProperties(sysEquipment, backup);
                backup.setDeleteFlag(1);
                sysEquipmentBackupMapper.insert(backup);
            }
            sysEquipmentMapper.delete(wrapper);
            //更新设备组中数据
            sysStationGroupEquipmentMapper.deleteByBind(eId);
            sysStationGroupEquipmentMapper.updateByBindEquipment(eId);
        }
        ;
        return 1;
    }

    /**
     * 修改设备状态
     *
     * @param equipmentIds
     * @param status       设备状态(3:故障;2正常;1:维修中;0:报废)
     * @return
     */
    @Override
    @Transactional
    public Integer updateStatus(List<String> equipmentIds, Integer status, String userId) {
        if (CollUtil.isEmpty(equipmentIds)) {
            return -1;
        }
        Integer flag = sysEquipmentMapper.updateStatus(equipmentIds, status, userId, com.qingcloud.adminbackend.utils.DateUtil.getCurrentDateTime());
        if (flag > 0) {
            //运维中和运维结束，传感器状态发生相应的变化
            if (WamingConstant.ONE.equals(status) || WamingConstant.THREE.equals(status)) {
                SysSensor sysSenso = new SysSensor();
                if (WamingConstant.ONE.equals(status)) {
                    //每次运维完成，清空运行周期记录
                    sysSenso.setPollutionCount(Long.valueOf(0));
                }
                sysSenso.setStatus(status);
                QueryWrapper<SysSensor> wrapper = new QueryWrapper<>();
                wrapper.in("equipment_id", equipmentIds);
                sysSensorMapper.update(sysSenso, wrapper);
            }
        }
        return flag;
    }

    /**
     * 修改校准状态
     *
     * @param equipmentIds
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Integer updateVerifyStatus(List<String> equipmentIds, String userId) {
        if (CollUtil.isEmpty(equipmentIds)) {
            return -1;
        }
        return sysEquipmentMapper.updateVerifyStatus(equipmentIds, userId, com.qingcloud.adminbackend.utils.DateUtil.getCurrentDateTime());
    }

    /**
     * 批量修改设备IP
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Integer updateIps(UpdateEquipmentIdDTO updateEquipmentIdDTO, String userId) {
        List<String> equipmentIds = updateEquipmentIdDTO.getEquipmentIds();
        if (CollUtil.isEmpty(equipmentIds)) {
            return -2;
        }
        //查询选中的设备是否是同一个协议的
        List<Integer> equipmentProtocol = sysEquipmentMapper.findEquipmentProtocol(equipmentIds);
        Set<Integer> protocolIds = new HashSet<>(equipmentProtocol);
        if (CollUtil.isEmpty(protocolIds)) {
            return -2;
        }
        if (protocolIds.size() > 1) {
            //选中设备的协议不同，不能同时进行设备控制操作。
            return -1;
        } else {
            //协议类型
            Integer protocolType = updateEquipmentIdDTO.getProtocolType();
            //修改IP
            if (WamingConstant.ONE.equals(protocolType)) {
                String host = updateEquipmentIdDTO.getHost();
                String port = updateEquipmentIdDTO.getPort();
                //MQTT
                if (StrUtil.isBlank(host) || StrUtil.isBlank(port)) {
                    return -4;
                } else {
                    sysEquipmentMapper.updateIp(equipmentIds, host.concat(":").concat(port));
                }
            } else if (WamingConstant.THREE.equals(protocolType)) {
                //网格化
                //判断IP地址是否在地址列表中
                String ipAdress = updateEquipmentIdDTO.getIpAdress();
                Boolean flag = checkIp(ipAdress);
                if (!flag) {
                    return -3;
                } else {
                    sysEquipmentMapper.updateIp(equipmentIds, ipAdress);
                }
            } else if (WamingConstant.FOUR.equals(protocolType)) {
                String port = updateEquipmentIdDTO.getPort();
                String ip = updateEquipmentIdDTO.getIpAdress();
                String https = updateEquipmentIdDTO.getHttpsPort();
                String websocket = updateEquipmentIdDTO.getWebsocketPort();
                //机器人修改Ip端口信息
                RobotDto robotDto = new RobotDto();
                robotDto.setIp(ip);
                robotDto.setHttpPort(Long.parseLong(port));
                robotDto.setHttpsPort(Long.parseLong(https));
                robotDto.setWebsocketPort(Long.parseLong(websocket));
                if (StrUtil.isBlank(port) || StrUtil.isBlank(ip)) {
                    return -4;
                }
                Boolean flag = checkIp(updateEquipmentIdDTO.getIpAdress());
                if (!flag) {
                    return -3;
                } else {
                    int up = robotService.updataIp(equipmentIds, robotDto);
                    if (up < 1) {
                        return -5;
                    }
                }
            }
        }
        return 1;
    }

    private Boolean checkIp(String ipAddress) {
        SysCommonConfig ipList = sysCommonConfigMapper.findByKey("station_ip_list");
        if (ipList == null) {
            return false;
        } else {
            String value = ipList.getValue();
            if (StrUtil.isBlank(value)) {
                return false;
            } else {
                List<String> ips = Arrays.asList(value.split(","));
                if (CollUtil.isEmpty(ips)) {
                    return false;
                } else {
                    if (!ips.contains(ipAddress)) {
                        return false;
                    }
                }
            }
            return true;
        }
    }

    /**
     * 通过文件修改校准状态
     *
     * @param excelFile
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult updateVerifyStatusByFile(MultipartFile excelFile, String userId) {
        try (InputStream inputStream = excelFile.getInputStream()) {
            if (!(FileMagic.valueOf(inputStream) == FileMagic.OOXML)) {
                //请上传excel xlsx类型文件，建议使用官方提供的模板;
                return new AjaxResult(WamingConstant.PART_SUCCESS, "请上传excel xlsx类型文件，建议使用官方提供的模板。", "");
            }
            //解析excel
            XSSFWorkbook workbook2007 = new XSSFWorkbook(excelFile.getInputStream());
            // 取得第一个sheet
            XSSFSheet sheet = workbook2007.getSheetAt(0);
            // 多少行
            int count = sheet.getPhysicalNumberOfRows();
            if (count < 1) {
                //Excel文件内容是空的
                return new AjaxResult(WamingConstant.FAILURE, "请选择设备", "");
            }
            XSSFCell cell;
            List<String> eqIds = new ArrayList<>();
            for (int i = 1; i < count; i++) {
                // 获取行对象
                XSSFRow row = sheet.getRow(i);
                int rowNum = row.getRowNum() + 1;
                if (row == null) {// 如果为空，不处理
                    continue;
                }
                //监测点编号
                cell = row.getCell(0);
                String equipmentId = ExcelUtil.getCellStringValue(cell);
                if (StrUtil.isBlank(equipmentId)) {
                    continue;
                }
                //判断设备权限
                Boolean flag = eqAuth(userId, equipmentId);
                if (!flag) {
                    return new AjaxResult(WamingConstant.FAILURE, "您对第" + rowNum + "行,设备" + equipmentId + "没有管理权限！", "");
                }
                eqIds.add(equipmentId);
            }
            sysEquipmentMapper.updateVerifyStatus(eqIds, userId, DateUtil.getCurrentDateTime());
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(WamingConstant.FAILURE, "未知错误", "");
        }
        return new AjaxResult(WamingConstant.SUCCESS, "", "校准成功");
    }

    /**
     * 判断设备的权限
     *
     * @param userId
     * @param equipmentId
     * @return
     */
    private Boolean eqAuth(String userId, String equipmentId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName())) {
            //有权限
            return true;
        }
        //获取登录用户有管理权限的订单
        List<String> manageOrderId = getManageOrderId(userId, SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName()));
        //查询设备的订单
        QueryWrapper<SysOrderEquipment> query = new QueryWrapper<>();
        query.eq("equipment_id", equipmentId);
        SysOrderEquipment sysOrderEquipment = sysOrderEquipmentMapper.selectOne(query);
        String orderId = "";
        if (sysOrderEquipment != null) {
            orderId = sysOrderEquipment.getOrderId();
        }
        if ((sysUser.getStationFlag() == 1 && StrUtil.isBlank(orderId)) || (sysUser.getStationFlag() == 1 && manageOrderId.contains(orderId))) {
            //有设备池权限
            return true;
        }
        return false;
    }

    private List<String> getManageOrderId(String userId, boolean isAdmin) {
        List<String> orderIds = new ArrayList<>();
        if (isAdmin) {
            List<SysOrder> sysOrders = sysOrderMapper.selectByMap(ImmutableMap.of("business_type", 2, "delete_flag", 0));
            sysOrders.forEach(t -> orderIds.add(t.getId()));
        } else {
            //查询用户能管理的客户
            List<SysUserOrgMgr> sysUserOrgMgrs = sysUserOrgMgrMapper.selectByMap(ImmutableMap.of("user_id", userId, "manage", 1));
            List<String> orgIds = sysUserOrgMgrs.stream().map(SysUserOrgMgr::getOrgId).collect(Collectors.toList());
            //订单
            List<String> orderIdList = sysOrderMapper.getAllManageOrderId(userId);
            orderIds.addAll(orderIdList);
            if (CollUtil.isNotEmpty(orgIds)) {
                QueryWrapper<SysOrder> query = new QueryWrapper<>();
                query.in("org_id", orgIds);
                query.eq("business_type", 2);
                query.eq("delete_flag", 0);
                List<SysOrder> sysOrders = sysOrderMapper.selectList(query);
                sysOrders.forEach(t -> orderIds.add(t.getId()));
            }
        }
        return orderIds;
    }

    /**
     * 设备控制
     *
     * @param equipmentIds
     * @param userId
     * @return
     */
    @Override
    public Integer equipmentControl(List<String> equipmentIds, String userId) {
        if (CollUtil.isEmpty(equipmentIds)) {
            return -2;
        }
        //查询选中的设备是否是同一个协议的
        List<Integer> equipmentProtocol = sysEquipmentMapper.findEquipmentProtocol(equipmentIds);
        Set<Integer> protocolIds = new HashSet<>(equipmentProtocol);
        if (CollUtil.isEmpty(protocolIds)) {
            return -2;
        }
        if (protocolIds.size() > 1) {
            //选中设备的协议不同，不能同时进行设备控制操作。
            return -1;
        } else if (protocolIds.contains(WamingConstant.PROTOCOL_CODE_PA)) {
            //不支持对选中设备进行设备控制操作。
            return -3;
        } else {
            if (protocolIds.contains(WamingConstant.PROTOCOL_CODE_MQTT)) {
                //蛙鸣MQTT协议
                return WamingConstant.PROTOCOL_CODE_MQTT;
            } else if (protocolIds.contains(WamingConstant.PROTOCOL_CODE_WT)) {
                //网格化
                return WamingConstant.PROTOCOL_CODE_WT;
            } else if (protocolIds.contains(WamingConstant.PROTOCOL_CODE_JWTH)) {
                //佳沃天河消杀设备
                return WamingConstant.PROTOCOL_CODE_JWTH;
            } else {
                return 0;
            }
        }
    }

    @Override
    @Transactional
    public AjaxResult equipmentExcelV2(MultipartFile file, String userId) throws IOException {
        List<SysProductType> sysProductTypes = sysProductTypeMapper.selectByMap(ImmutableMap.of());
        InputStream in = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(in);
        if (in != null) {
            in.close();
        }
        if (workbook != null) {
            // 遍历每个Sheet
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
            // 遍历每一行
            List<SysEquipment> sysEquipments = new ArrayList<>();
            List<String> equipmentIds = new ArrayList<>();
            for (int r = 1; r < rowCount; r++) {
                Row row = sheet.getRow(r);
                /*组装设备*/
                SysEquipment sysEquipment = new SysEquipment();
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析设备模板第" + r + "行第1列设备编号不能为空！", null);
                }
                if (!CommonUtil.isLetterDigit(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析设备模板第" + r + "行第1列设备编号输入错误！", null);
                }
                sysEquipment.setEquipmentId(ExcelUtil.getCellStringValue(row.getCell(0)));
                if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(1)))) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析设备模板第" + r + "行第2列产品型号不能为空！", null);
                }
                //产品型号
                sysProductTypes.forEach(it -> {
                    if (it.getProductType().equals(ExcelUtil.getCellStringValue(row.getCell(1)))) {
                        sysEquipment.setProductType(ExcelUtil.getCellStringValue(row.getCell(1)));
                    }
                });
                if (StrUtil.isBlank(sysEquipment.getProductType())) {
                    return new AjaxResult(WamingConstant.FAILURE, "解析设备模板第" + r + "行第2列产品型号不匹配！", null);
                }
                if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(2)))) {
                    //出厂厂商
                    sysEquipment.setManufacturer(ExcelUtil.getCellStringValue(row.getCell(2)));
                }
                if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(3)))) {
                    //物联网卡号
                    sysEquipment.setPhoneNum(ExcelUtil.getCellStringValue(row.getCell(3)));
                }
                if (equipmentIds.contains(sysEquipment.getEquipmentId())) {
                    return new AjaxResult(WamingConstant.FAILURE, "导入的设备编号" + sysEquipment.getEquipmentId() + "重复");
                }
                equipmentIds.add(sysEquipment.getEquipmentId());
                sysEquipment.setCreateBy(userId);
                sysEquipment.setCreateDt(new Date());
                sysEquipment.setStatus(1);
                sysEquipment.setRunningMode(2);
                sysEquipments.add(sysEquipment);
            }
            if (sysEquipments.size() > 0) {
                List<String> ids = baseMapper.findEquipments(equipmentIds);
                if (ids.size() > 0) {
                    String equipmenIdJson = StringUtil.listToString(ids);
                    return new AjaxResult(WamingConstant.FAILURE, "设备" + equipmenIdJson + "已经存在");
                }
                //删除设备避免重复
                baseMapper.deleteEquipments(sysEquipments);
                //添加设备
                baseMapper.insertEquipments(sysEquipments);
            }
            return sensorExcel(workbook);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
    }

    /**
     * 传感器导入
     *
     * @param workbook
     * @return
     */
    @Transactional
    public AjaxResult sensorExcel(Workbook workbook) {
        // 遍历每个Sheet
        Sheet sheet = workbook.getSheetAt(1);
        int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
        // 遍历每一行
        List<SensorParamDTO> sensorParams = new ArrayList<>();
        List<String> sensorIds = new ArrayList<>();
        List<SysSensorFactor> sysSensorFactors = new ArrayList<>();
        List<SysDictionaryConfig> sysDictionaryConfigList = sysDictionaryConfigMapper.findByType(23);
        List<SysSensorFactorConfig> sysSensorFactorConfigs = sysSensorFactorConfigMapper.selectByMap(ImmutableMap.of());
        List<String> equpmentIds = new ArrayList<>();
        Map<String, String> factorMap = new HashMap<>();
        for (int r = 1; r < rowCount; r++) {
            Row row = sheet.getRow(r);
            if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板第" + r + "行第1列设备编号不能为空！", null);
            }
            if (!CommonUtil.isLetterDigit(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板第" + r + "行第1列设备编号输入错误！", null);
            }
            equpmentIds.add(ExcelUtil.getCellStringValue(row.getCell(0)));
        }
        if (equpmentIds.size() > 0) {
            List<String> equipments = sysEquipmentMapper.findEquipments(equpmentIds);
            List list = CommonUtil.removeAll(equpmentIds, equipments);
            if (list.size() > 0) {
                String equipmentJson = StringUtil.objectString(list);
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板设备编号" + equipmentJson + "不存在！", null);
            }

            List<EquipmentListDTO> listDTOS = sysEquipmentMapper.findFactorByEqupmentId(equpmentIds);
            listDTOS.forEach(it -> {
                factorMap.put(it.getEquipmentId(), it.getUseSensorFactors());
            });
        }
        for (int r = 1; r < rowCount; r++) {
            Row row = sheet.getRow(r);
            /*组装传感器*/
            SensorParamDTO sensorParam = new SensorParamDTO();
            if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(0)))) {
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板第" + r + "行第1列设备编号不能为空！", null);
            }
            sensorParam.setEquipmentId(ExcelUtil.getCellStringValue(row.getCell(0)));
            if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(1)))) {
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板第" + r + "行第2列传感器编号不能为空！", null);
            }
            //传感器编号
            sensorParam.setSensorId(ExcelUtil.getCellStringValue(row.getCell(1)));
            if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(2)))) {
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板第" + r + "行第3列传感器种类不能为空！", null);
            }
            sysDictionaryConfigList.forEach(it -> {
                if (it.getName().equals(ExcelUtil.getCellStringValue(row.getCell(2)))) {
                    //传感器种类
                    sensorParam.setCatagory(Integer.valueOf(it.getCode()));
                }
            });
            if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(3)))) {
                //出厂时间
                sensorParam.setFactoryTime(ExcelUtil.getCellStringValue(row.getCell(3)));
            }
            if (!StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(4)))) {
                //生产厂商
                sensorParam.setSupplier(ExcelUtil.getCellStringValue(row.getCell(4)));
            }
            if (StringUtils.isEmpty(ExcelUtil.getCellStringValue(row.getCell(5)))) {
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板第" + r + "行第6列监测因子不能为空！", null);
            }
            String factors = factorMap.get(sensorParam.getEquipmentId());
            List<String> lists = Arrays.asList(factors.split(","));
            //传感器的监测因子
            List<String> list = Arrays.asList(ExcelUtil.getCellStringValue(row.getCell(5)).split(","));
            if (!lists.containsAll(list)) {
                return new AjaxResult(WamingConstant.FAILURE, "解析传感器模板第" + r + "行第6列监测因子型号不符！", null);
            }
            list.forEach(it -> {
                sysSensorFactorConfigs.forEach(factor -> {
                    if (it.equals(factor.getFactorDesc())) {
                        SysSensorFactor sysSensorFactor = new SysSensorFactor();
                        sysSensorFactor.setFactorId(factor.getFactorId());
                        sysSensorFactor.setSensorId(sensorParam.getSensorId());
                        sysSensorFactor.setDeleteFlag(0);
                        sysSensorFactors.add(sysSensorFactor);
                    }
                });
            });
            sensorParam.setStatus(1);
            sensorParams.add(sensorParam);
            sensorIds.add(sensorParam.getSensorId());
        }
        if (sensorParams.size() > 0) {
            List<String> ids = sysSensorMapper.existSensors(sensorIds);
            if (ids.size() > 0) {
                String sensorsIdJson = StringUtil.listToString(ids);
                return new AjaxResult(WamingConstant.FAILURE, "传感器" + sensorsIdJson + "已经存在");
            }
            //添加传感器
            int count = sysSensorMapper.insertSensors(sensorParams);
            if (count > 0) {
                //添加传感器的监测因子
                sysSensorFactorMapper.insertSensorFactor(sysSensorFactors);
            }
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "导入成功");
    }

    @Override
    public StationMiniInfo getEqBind(String equipmentId) {
        StationMiniInfo res = sysEquipmentMapper.getEqBind(equipmentId);
        return res;
    }

    @Override
    public Long existEquipment(String equipmentId) {
        return sysEquipmentMapper.existEquipment(equipmentId);
    }

    /**
     * 获取所有气溶胶可用IP
     *
     * @return ip列表
     */
    @Override
    public List<String> getAerosolIpList() {
        SysCommonConfig ipConfig = sysCommonConfigMapper.findByKey("station_ip_list");
        if (Objects.nonNull(ipConfig)) {
            return Arrays.asList(ipConfig.getValue().split(",").clone());
        }
        return Collections.emptyList();
    }

    /**
     * 按业务种类查询需要同步的设备信息
     */
    @Override
    public List<EquipmentSyncDTO> findEquipmentSyncInfo(Integer businessType) {
        return sysEquipmentMapper.findEquipmentSyncInfo(businessType);
    }

    /**
     * 按订单查询设备编号
     *
     * @param projectId 订单编号
     * @return
     */
    @Override
    public List<EquipmentProjectInfoDTO> findByOrder(String projectId) {
        return sysEquipmentMapper.findInfoByOrder(projectId);
    }

    /**
     * 查询设备项目信息
     */
    @Override
    public List<EquipmentProjectInfoDTO> findEquipmentOrderInfo(List<String> equipmentIds) {
        return sysEquipmentMapper.findInfoByIds(equipmentIds);
    }

    /**
     * 设备编号筛选业务种类
     *
     * @param eidSet       设备编号集合
     * @param businessType 业务种类
     */
    @Override
    public Set<String> filterBusinessType(Set<String> eidSet, Integer businessType) {
        if (CollUtil.isEmpty(eidSet)) {
            return Collections.emptySet();
        }
        return sysEquipmentMapper.filterBusinessType(eidSet, businessType);
    }

    @Override
    public List<String> equipmentByProductType(String productType) {
        return sysEquipmentMapper.selectEquipmentByProductType(productType);
    }

    @Override
    public GatewayInfo gatewayInfo(String equipmentId) {
        LambdaQueryWrapper<SysEquipment> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysEquipment::getEquipmentId, equipmentId);
        SysEquipment sysEquipment = sysEquipmentMapper.selectOne(queryWrapper);
        final GatewayInfo gatewayInfo = new GatewayInfo();
        BeanUtils.copyProperties(sysEquipment, gatewayInfo);
        if (Integer.valueOf(1).equals(sysEquipment.getOnlineStatus())) {
            gatewayInfo.setOnlineStatus("在线");
        } else {
            gatewayInfo.setOnlineStatus("离线");
        }
        //查询网关状态
        if (Objects.nonNull(gatewayInfo.getGatewayId()) && gatewayInfo.getGatewayId() > 0) {
            final JSONObject instance = dataFusionApiHelper.findComponentInstance(gatewayInfo.getGatewayId());
            if (instance != null) {
                final Integer state = instance.getInteger("state");
                if (Integer.valueOf(0).equals(state)) {
                    gatewayInfo.setGatewayState("停止");
                } else if (Integer.valueOf(1).equals(state)) {
                    gatewayInfo.setGatewayState("正常");
                } else {
                    gatewayInfo.setGatewayState("未知");
                }
            } else {
                gatewayInfo.setGatewayState("无");
            }
        } else {
            gatewayInfo.setGatewayState("无");
        }
        return gatewayInfo;
    }

    /**
     * 查询设备解码器
     */
    @Override
    public List<EquipmentDecoder> decoders(String equipmentId) {
        List<EquipmentDecoder> resultList = new ArrayList<>();
        final EquipmentDecoder allDecoder = new EquipmentDecoder();
        allDecoder.setName("所有日志");
        allDecoder.setComponentId(0);
        resultList.add(allDecoder);

        List<EquipmentDecoder> decoders = sysEquipmentMapper.findMessageDecoders(equipmentId);
        resultList.addAll(decoders);
        return resultList;
    }

    @Override
    public List<EquipmentDecodeMessage> decodeMessage(String equipmentId, Integer componentId) {
        Long queryTime = System.currentTimeMillis();
        //先查询是否有最新数据
        List<EquipmentDecodeMessage> messageList = decodeRecordMapper.findByTime(equipmentId, componentId, queryTime);
        if (CollUtil.isNotEmpty(messageList)) {
            for (EquipmentDecodeMessage message : messageList) {
                if (StrUtil.isNotBlank(message.getData())) {
                    message.setDataList(JSONArray.parseArray(message.getData(), ProductParseData.class));
                    message.setData("");
                }
            }
            //有消息直接返回
            return messageList;
        }
        //没有消息，等待状态中心通知
        eqcenterApi.decodeMessage(equipmentId, componentId);
        messageList = decodeRecordMapper.findByTime(equipmentId, componentId, queryTime);
        for (EquipmentDecodeMessage message : messageList) {
            if (StrUtil.isNotBlank(message.getData())) {
                message.setDataList(JSONArray.parseArray(message.getData(), ProductParseData.class));
                message.setData("");
            }
        }
        return messageList;
    }

}
